How to load js scripts dynamically?

Asked

Viewed 4,141 times

9

I am 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 that unnecessary scripts are not loaded.

The problem is I don’t know how to do that. I thought about the Requirejs, but as I’m working with angular I ended up leaving it alone, because the only way I found to work with AMD using angular didn’t seem 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 don’t know how to use this to actually load the scripts.

  • Why not directly execute a eval or insert a <script> with the DOM code after ajax returns?

  • Although at first it seems like a good idea, selective loading of scripts ends up resulting in future problems, such as higher server load due to the higher number of requests required, longer script interpretation time and longer latency time. I strongly recommend abandoning this method or assessing whether this is really the best way forward.

1 answer

10

No need for Ajax, just create a type element script and Research in 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 an Handler for the event load:

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

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

Browser other questions tagged

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