1

Running require(['pages/home']) will work once but if I use require(['pages/home']) again then it won't run.
The module "pages/home" is a file named "home.js" in a directory named "pages".

main.js

require(['pages/home']);

pages/home.js

define('pages/home', function() {
    console.log('running pages/home module');
});

3 Answers 3

4

RequireJS modules are singletons. It loads a module once and only once. If a module has been loaded already, what you get if you load it again is a reference to the same module as originally loaded. The factory function you pass to define won't be run a second time.

So what you are seeing is exactly what is expected.

Sign up to request clarification or add additional context in comments.

Comments

0

Static code in modules isn't supposed to be evaluated more than once, just like a script loaded through a normal <script> tag won't be run more than once during the page load.

Imagine if a module contained code like:

define('my-module', function () {
  var foo = foo || 0;
  var bar = ++foo;
});

You should expect bar and foo to both === 1, but if the module was run repeatedly and a global foo existed, that may not be the case. Admittedly, this is a very contrived example, but evaluating a module repeatedly could cause serious problems.

Comments

0

Make it return a function/object that can be executed after you require it.

define('pages/home', function() {
    return function(){
       console.log('running pages/home module');
    };
});
require(['pages/home'], function(resultFunc){
   window.YourFunc = resultFunc;
});

Now you can execute your function whenever you want

3 Comments

The entire point of AMD or any other moduling system is to prevent the need for using global variables. -1.
@SecondRikudo I know it is a bad practice to use global variables. I am just giving an example of what the result of the factory function of requirejs would look like. I would expect that he/she would store the outcome in some kind of namespace that he/she uses inside his/her application.
You can't really "expect" anything from the asker.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.