js动态加载js和css

一、动态加载CSS<br />动态创建css样式有两种方式:<br />1、动态插入css外部文件的方法:<br />function loadStyle(url){<br />  var link = document.createElement('link');<br />    link.type = 'text/css';<br />    link.rel = 'stylesheet';<br />    link.href = url;<br />    var head = document.getElementsByTagName('head')[0];<br />    head.appendChild(link);<br />}<br />loadStyle('test.css');

2、动态加载css代码片段

function loadCssCode(code){
var style = document.createElement('style');
    style.type = 'text/css';
    style.rel = 'stylesheet';
    try{
        //for Chrome Firefox Opera Safari
        style .appendChild(document.createTextNode(code));
    }catch(ex){
        //for IE
        style.styleSheet.cssText = code;
    }
    var head = document.getElementsByTagName('head')[0];
    head.appendChild(style);
}
loadCssCode('body{background-color:#f00}');

二、动态加载js

1、异步加载,并加载到前台资源库

function loadJsCallback(sid, jsurl, callback) {
 var nodeHead = document.getElementsByTagName('head')[0];
 var urlStr = jsurl.split(',');
 if(document.getElementById(sid + "JS0") == null){
  var urlLength = urlStr.length;
  for(var i = 0; i < urlStr.length; i++){
   var nodeScript = document.createElement('script');
   nodeScript.setAttribute('type', 'text/javascript');
   nodeScript.setAttribute('src', urlStr[i]);
   nodeScript.setAttribute('id', sid + 'JS' + i);
   if(callback != null){
    nodeScript.onload = nodeScript.onreadystatechange = function(curTarget) {
     if(nodeScript.ready){
      return false;
     }
     if(!nodeScript.readyState || nodeScript.readyState == "loaded"
       || nodeScript.readyState == 'complete'){
      urlLength -= 1;
      if(0 != urlLength){
       return false;
      }else{
       nodeScript.ready = true;
       callback();
      }
     }
    };
   }
   nodeHead.appendChild(nodeScript);
  }
 }else{
  if(callback != null){
   callback();
  }
 }
}

相关推荐