动态加载Js方法2+动态加载Css

关于动态加载JS,我们之前有谈到过一个比较好的方法:动态加载Js方法1
现在这里给出第二种方法,本人觉得没有上一个方法好:

/* 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

引用通告地址: 点击获取引用地址
标签: WEB
评论: 0 | 引用: 0 | 阅读: 638 | 打印 | 打包 | 转发
发表评论
昵 称: 密 码:
网 址: 邮 箱:
验证码: 验证码图片 选 项:
头 像:
内 容:
  • 粗体
  • 斜体
  • 下划线
  • 插入图像
  • 超链接
  • 电子邮件
  • 插入引用