Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

requireJS module loading

I need some help with the concept of only loading modules when they are needed using requireJS

this is my main.js

require(['jquery', 'path/somemodule'],
function($, somemodule) {
$(document).ready(function() {
    somemodule.init()
})

})

and in the somemodule.js

 define(['jquery', 'path/someothermodule'], function ($, someothermodule) {
 "use strict";
var somemodule;

somemodule = {
init: function () {
    someothermodule.init()
}
}
return somemodule;
)}

right now somemodule.js and someothermodule.js is loaded on all pages. How do I only load it when it's needed?

like image 531
Newcoma Avatar asked Jan 31 '26 00:01

Newcoma


1 Answers

When you require a module2 from module1 using the standard define() syntax module1 will not load/run until module2 has been fully loaded. That looks like this:

// inside module1
define(['module2'], function(mod2) {
   // we don't get here until AFTER module2 has already been loaded
});

An alternative to lazy-load module2 looks like this:

// inside module1
define([], function() {
   require(['module2'], function(mod2) {
       // we don't get here until AFTER module2 has already been loaded
   });
   // but we DO get here without having loaded module2
});

Now you have to program somewhat carefully to make sure you don't run into any issues with asynchronicity.

In your case you can modify your main.js file

require(['jquery'],
function($) {
    // jquery is loaded, but somemodule has not

    if(thisPageNeedsSomeModule) {
        require(['path/somemodule'],
        function(somemodule) {
            // now somemodule has loaded
            $(document).ready(function() {
                somemodule.init()
            })
        });
    }
})
like image 73
Mike Edwards Avatar answered Feb 02 '26 15:02

Mike Edwards



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!