Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

today I've been working on loading dynamic javascript code (files). The solution I use is :

function loadScript(scriptUrl) {
        var head = document.getElementsByTagName("head")[0];
        var script = document.createElement('script');
        script.id = 'uploadScript';
        script.type = 'text/javascript';
        script.src = scriptUrl;
        head.appendChild(script);

the problem with this is that I don't know how to make sure WHEN the script contents are executed. Since the script contains classes (well JS classes), I wrote down a function that is called through setTimeout and checks if those objects are defined. This is not flexible as it is not automatical. So? Are there ways to load those scripts and have a reliable notification on when they have been executed?

You can use jquery's getScript and pass a callback function.

$.getScript("test.js", function(){
   alert("Script loaded and executed.");

See: jquery.

+1. This way you can support dependency and load them in order by nesting the getScript calls in the callback functions. – Fosco Aug 19, 2010 at 15:06 You can check out the jQuery source code, it can be easily implemented using plain JavaScript, see: gist.github.com/538106 – tszming Aug 19, 2010 at 15:20 Note that as per jQuery docs currently : The callback is fired once the script has been loaded but not necessarily executed. i.e. It doesn't guarantees execution of script. – Ankit Feb 19, 2016 at 9:03

The easiest way short of a JS library is to make an XMLHttpRequest and eval() the return. Your "onload" would be when the data is returned, and "oninit" would be right after you've eval'd.

EDIT: If you want to sequence this, you can create an AssetLoader that takes an array of scripts and won't eval() a script until the one preceding it has been fetched and initialized.

EDIT 2: You can also use the script.onload stuff in the post referenced in the comments. The eval method has a slight advantage in that you can separate and control the load and execution portions of the script import.

EDIT 3: Here's an example. Consider a file called foo.js that contains the following:

function foo () { alert('bar');

Then execute the following from another page in your browser:

function initScript (scriptString) { window.eval(scriptString); function getScript (url, loadCallback, initCallback, callbackScope) { var req = new XMLHttpRequest(); req.open('GET', url); req.onreadystatechange = function (e) { if (req.readyState == 4) { if (loadCallback) loadCallback.apply(callbackScope); initScript.call(null, req.responseText); if (initCallback) initCallback.apply(callbackScope); req.send(); function fooScriptLoaded () { alert('script loaded'); function fooScriptInitialized () { alert('script initialized'); foo(); window.onload = function () { getScript('foo.js', fooScriptLoaded, fooScriptInitialized, null);

You will see the alerts "script loaded", "script initialized", and "bar". Obviously the implementation of XMLHttpRequest here isn't complete and there are all sorts of things you can do for whatever scope you want to execute the script in, but this is the core of it.

After eval() the script has been initialized. You can throw a try-catch block around it to see if any errors prevent the script from initializing. – sevenflow Aug 19, 2010 at 15:13

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.