I already ask similar question: Requirejs, what it means "Requirejs loads each module once"
but in that topic no one answer the main question, because i asked in
I changed your main.js
to log to the console
require(['test1', 'test2', 'counter'], function(test1, test2, counter) {
console.log("Executing main");
console.log(counter.get());
});
In addition I have an index.html
My Counter Demo
My Counter Demo
After loading index.html
and then opening the web console I have
[22:04:09.077] "Executing counter"
[22:04:09.077] "Executing test1"
[22:04:09.077] "Executing test2"
[22:04:09.077] "Executing main"
[22:04:09.078] 2
To make it more clear what happens I suggest to substitute the log messages
Executing counter
-> Creating the counter AMD module
Executing test1
-> Incrementing the counter in module "test1"
Executing test2
-> Incrementing the counter in module "test2"
"Executing main"
-> Retrieving the counter value in module "main"
The I get the following result in the console log
[22:16:46.368] file:///C:/Users/User/Documents/requirejs-counter2/css/main.css
[22:16:46.368] file:///C:/Users/User/Documents/requirejs-counter2/scripts/require.js
[22:16:46.369] file:///C:/Users/User/Documents/requirejs-counter2/scripts/main.js
[22:16:46.588] file:///C:/Users/User/Documents/requirejs-counter2/scripts/test1.js
[22:16:46.589] file:///C:/Users/User/Documents/requirejs-counter2/scripts/test2.js
[22:16:46.590] file:///C:/Users/User/Documents/requirejs-counter2/scripts/counter.js
[22:16:46.381] "Creating the counter AMD module"
[22:16:46.381] "Incrementing the counter in module "test1""
[22:16:46.381] "Incrementing the counter in module "test2""
[22:16:46.381] "Retrieving the counter value in module "main""
[22:16:46.381] 2
The counter module is only loaded once and thus creating the counter object only once. You may consider it to be a Singleton
.