0

In this question it is clearly shown how to programmatically inject a new script in an HTML page.

What I'd like to ask, however, is if such injection is blocking, that is, it'll wait for the injected script to be loaded and executed before calling the next line.

For example

function inject(script_url) { ... }

// somewhere in the code
inject('/path/to/script.js');
func_in_script(); // <-- will "func_in_script" be defined at this point?

EDIT:

This is what I found out trying:

If I use native JS like

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
script.async = false; // !!!
script.defer = false; // !!!
document.head.appendChild(script);

Then the functions in the loaded script are not immediately available after the call to appendChild(); however if I use jQuery like:

$('<script/>', {
    type: 'text/javascript',
    src: url,
    async: false,
    defer: false
}).appendTo('head');

It works as I'd like it to.

Community
  • 1
  • 1
Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81

0 Answers0