How to load scripts js dynamically?

8

I'm developing a web system that needs to load js files dynamically. The reason for this is that there is a necessary logic for selecting which scripts are required, so unnecessary scripts are not loaded.

The problem is that I do not know how to do this. I thought about the RequireJS, but as I'm working with angular, I ended up letting it go, because the only way I found working with AMD using angular was not very natural.

How can I load scripts dynamically? Basically, I thought of an ajax call to a web service url that would be able to select the scripts and return this data, but I do not know how to use it to actually load the scripts.

    
asked by anonymous 02.05.2014 / 01:03

1 answer

9

Do not need Ajax, simply create a script element and inject into the DOM:

var script = document.createElement('script');
script.src = ""; // URL do seu script aqui
document.body.appendChild(script);

You can control what to do after loading with a handler for the load event:

script.onload = function() {
    // daqui você pode carregar seus scripts dependentes
};

If you want to build a simple asynchronous scripting system, these are the basic building blocks.

    
02.05.2014 / 01:11