Dynamically loading Javascript files and load completion events

前端 未结 3 973
攒了一身酷
攒了一身酷 2021-01-19 07:32

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

function loadScript(scriptUrl) {
        var head = document.get         


        
相关标签:
3条回答
  • 2021-01-19 07:38

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

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

    See: jquery.

    0 讨论(0)
  • 2021-01-19 07:41

    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 讨论(0)
  • 2021-01-19 07:49

    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.

    0 讨论(0)
提交回复
热议问题