Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I am developing a web app using jQuery and RequireJS for dependency management. Some of my Javascript files have to be loaded lazily when some events happend, so I have written these events like this:

$("#pf-content").on("click", "#link", function() {
    require(["another_js"], function(another_js){
         //Initialization code from another_js.js
    });
});

The above code works, but I understand it's not the best way to do this, because the entire code has to be filled with "require" statements, wherever a lazy load would be neccesary.

Is there any other more elegant way to lazy load a Javascript file using jQuery and RequireJS?

Thank you very much in advance

share|improve this question
    
This looks like an XY problem. Why do you want to load that module at the very last second, just before using it? Knowing the "why" is important because there may be solutions that you have not considered. Or considerations that you have not thought about. Also, whether this way or that way is more elegant than the other is really a matter of opinion. You should specify what concrete results you are after. –  Louis May 28 at 16:15
    
@Louis, thank you for your comment. I need the JS files to be loaded lazily in order to load any page of my web app as fast as possible. I am using RequireJS to manage my JS dependencies, so I am trying to load them lazily with it. –  Genzotto May 28 at 16:25

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.