Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute javascript after external javascript document has loaded

Tags:

javascript

dom

I want to include a remote js file and then invoke a function once that has finished executing. I thought I could do something like this:

var sc = document.createElement('script');
sc.setAttribute('type', 'text/javascript');
sc.setAttribute('src', src);
sc.innerHTML = "alert('testing');"
parentNode.appendChild(sc);

Turns out, the alert('testing') gets wiped out be whatever is in the file. Is there anyway to do this?

like image 660
ChrisDiRulli Avatar asked Jul 28 '26 16:07

ChrisDiRulli


1 Answers

This function will load library from scriptPath and execute passed handler function once script is loaded:

loadExternalScript : function(scriptPath, handler) {

    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = scriptPath;
    script.charset = 'utf-8';

    script.onload = handler;

    head.appendChild(script);

}
like image 160
Rudi Avatar answered Jul 30 '26 06:07

Rudi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!