Load dependencies on demand

Asked

Viewed 412 times

2

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

Starting from this principle, I saw in Angular initially the idea of uploading the files on demand, which in my view greatly improves performance regarding the request. But I’m on Angular’s baby step. So I did the following, I divided my script by functionality and responsibility being that it was no longer very big, but I don’t need to load everything at once! (component type).

Here’s what you get. index with Loader more Frufru with animations chained in css and not just a fake gif, then I did an ajax to load my core (content) of the site so that the html was not heavy because I have elements (video/img/svg...). So I don’t want to carry it all in one stroke. Cool! I used Require.js funfo!

Question: I want to play require['file.js'] within the function I handle the Ajax request,to load only when I have the return? Is it possible? I don’t want to upload 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;
    ...}
    }
}

1 answer

2

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

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

You’ll have to move the call from require into the function that deals with the response of the ajax call: your onreadystatechange.

And there, everything that depends on the module events you play inside the past callback pro require... probably that callback should get an argument for you to have access to the module itself.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.