您的位置:首页 > Web前端 > JavaScript

如何动态加载Javascript脚本

2010-04-01 17:21 543 查看
一类方法,可以动态加载Js脚本,支持所有浏览器,方法如下:
function LoadScript( url ) {
        document.write('<scr'+'ipt type="text/javascript" scr="' + url + '"></scr' + 'ipt>');
}
调用方法:
LoadScript('../fckconfig.js');
以下是个完整的例子:
<script type="text/javascript">
   
function loadScript(url)
{
   document.write('<script src="', url, '" type="text/javascript"></script>');
}

loadScript(navigator.appName.indexOf("Microsoft") != -1 ? "ie_msg.js" : "ns_msg.js");

</script>
 
 
现在这里给出第二种方法,本人觉得没有上一个方法好:
/* Impot Common script*/
    function addJS(jsfile)
    {
        var head = document.getElementsByTagName('HEAD').item(0);
        var script = document.createElement('SCRIPT');
        script.src = jsfile;
        script.type = "text/javascript";
        head.appendChild(script);
    }
 
    function addCSS(cssfile) { 
        var head = document.getElementsByTagName('HEAD').item(0);
        var style = document.createElement('link');
        style.href = cssfile;
        style.rel = 'stylesheet'
        style.type = 'text/css';
        head.appendChild(style);
    }
   
/* LoadScripts at here.*/

    function LoadScripts()
    {
        addJS(_ResourcePath+"Scripts/ToolBar.js");
    }
   
    function LoadCSS()
    {
        addCSS(_ResourcePath+"Styles/default.css");
    }

以下是比较标准的例子,供参考:

function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}

loadjscssfile("myscript.js", "js")         //dynamically load and add this .js file
loadjscssfile("javascript.php", "js")   //dynamically load "javascript.php" as a JavaScript file
loadjscssfile("mystyle.css", "css")    //dynamically load and add this .css file
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息