Dynamically load a JavaScript file

后端 未结 28 3545
说谎
说谎 2020-11-22 06:56

How can you reliably and dynamically load a JavaScript file? This will can be used to implement a module or component that when \'initialized\' the component will dynamical

28条回答
  •  说谎
    说谎 (楼主)
    2020-11-22 07:49

    i've used yet another solution i found on the net ... this one is under creativecommons and it checks if the source was included prior to calling the function ...

    you can find the file here: include.js

    /** include - including .js files from JS - bfults@gmail.com - 2005-02-09
     ** Code licensed under Creative Commons Attribution-ShareAlike License 
     ** http://creativecommons.org/licenses/by-sa/2.0/
     **/              
    var hIncludes = null;
    function include(sURI)
    {   
      if (document.getElementsByTagName)
      {   
        if (!hIncludes)
        {
          hIncludes = {}; 
          var cScripts = document.getElementsByTagName("script");
          for (var i=0,len=cScripts.length; i < len; i++)
            if (cScripts[i].src) hIncludes[cScripts[i].src] = true;
        }
        if (!hIncludes[sURI])
        {
          var oNew = document.createElement("script");
          oNew.type = "text/javascript";
          oNew.src = sURI;
          hIncludes[sURI]=true;
          document.getElementsByTagName("head")[0].appendChild(oNew);
        }
      }   
    } 
    

提交回复
热议问题