开发者

Dynamically loading Javascript files and load completion events

开发者 https://www.devze.com 2023-01-12 12:17 出处:网络
today I\'ve been working on loading dynamic javascript code (files). The solution I use is : function loadScript(scriptUrl) {

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.c开发者_JS百科reateElement('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.


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.


You could use a counter variable, and a kind of callback:

var scriptsToLoad = 10;
var loadedScripts = 0;
//...
function increaseLoadCount() {
loadedScripts++;
if(loadedScripts == scriptsToLoad) {
alert("start here");
}
}

//script1-10.js
increaseLoadCount();

Maybe a bit nicer than with a timeout..

0

精彩评论

暂无评论...
验证码 换一张
取 消