Loading Javascript Dynamically and how to check if the script exists

后端 未结 9 554

I am using the following technique to load up Javascript dynamically:

var script = document.createElement(\"script\");
script.type = \"text/javascript\";
scr         


        
相关标签:
9条回答
  • 2020-12-01 16:52

    In the onload event, there are status codes. 200 is good, 404 as you may recall means a file is not found. Helpful?

    0 讨论(0)
  • 2020-12-01 16:55

    Loading a script dynamically is much more simple:

    var script = document.createElement('script');
    script.onload = function () {
      main_function();  // Main function to call or anything else or nothing  
    };
    script.src = "yourscript.js";
    document.head.appendChild(script);    
    
    0 讨论(0)
  • 2020-12-01 16:56

    What JavaScript library do you use?

    In jQuery if you load the script via Ajax, you have an option to run a success callback function (and other types of callbacks)...

    There is also a dedicated function for loading scripts: $.getScript()

    0 讨论(0)
  • 2020-12-01 16:59

    It's pretty easy, Internet Explorer will trigger an onreadystatechange event while others will trigger a onload event for the script object.

    var newScript;
    var loadFunc = function ()
    {
        alert("External Javascript File has been loaded");
    };
    newScript = document.createElement('script');
    newScript.setAttribute('type','text/javascript');
    newScript.setAttribute('src','file.js');
    
    //IE triggers this event when the file is loaded
    if (elm.attachEvent)
    {
        newScript.attachEvent('onreadystatechange',function() 
        {
            if (newScript.readyState == 'complete' || newScript.readyState == 'loaded')
                loadFunc();
        });
    }
    
    //Other browsers trigger this one
    if (newScript.addEventListener)
        newScript.addEventListener('load', loadFunc, false);
    
    document.getElementsByTagName('head')[0].appendChild(newScript);
    
    0 讨论(0)
  • 2020-12-01 17:00

    You can append an onload attribute and in that attribute, you can call a function which will be executed after the JS file has loaded.

    Check the code:

    var jsElement = document.createElement("script");
    jsElement.type = "application/javascript";
    jsElement.src = "http://code.jquery.com/jquery-latest.min.js";
    jsElement.setAttribute("onload","getMeAll()");
    document.body.appendChild(jsElement);
    function getMeAll(){
        //your code goes here
    }
    

    Hope this helps.

    0 讨论(0)
  • 2020-12-01 17:02

    One way would be to define a variable in the script you include and then check whether this variable is defined, or not.

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