Load dependencies on demand

2

I understand by dependency, the need for your script to need or is accessing in some way some method / property or properly an object encapsulated in another javascript file, be it a framework or not! Right?

Based on this principle, I initially saw the idea of loading the files on demand, which in my view greatly improves the performance of the requisition. However I am in the baby step of the Angular. So I did the following, I divided my script by functionality and responsibility being that it was not too big, but I do not have to load everything at once! (component type).

What I get is the following I have .index with loader more frufru with css-linked animations and not just a fake gif, so I did an ajax to load my core (content) of the site so that the html did not get heavy because I have elements (video / img / svg ...). So I do not want to carry this all in one go. Nice! I used the Funk Require.js!

Question: I want to play require['file.js'] within the function that handles the Ajax request, to load only when I have the return? It's possible? I do not want to load files as soon as I load other modules!

(function(){

 require([ 'events' ], function() {
    console.log("Ok Carregou arquivo eventos")
  });

})()

var wp = document.querySelector(".wrapper");
function Ajax (mtd, file){
obj = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP")
obj.open(mtd, file, true);
obj.send(null);
obj.onreadystatechange = function(){
    if(obj.readyState == 4 && obj.status == 200){
    wp.innerHTML=obj.responseText;
    ...}
    }
}
    
asked by anonymous 27.03.2015 / 01:51

1 answer

2

It is possible, but it is not so in the example you gave.

In your example, you create a function and then call the method require face, outside of ajax.

You will have to move the call from require to the function that handles the response of the ajax call: its onreadystatechange .

And, whatever depends on the module events you play into the callback passed to require ... probably this callback should receive an argument for you to have access to the module itself.

    
27.03.2015 / 05:09