码迷,mamicode.com
首页 > Web开发 > 详细

动态加载js和css

时间:2018-01-19 19:54:53      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:append   tee   sso   tty   get   div   代码   css样式   tno   

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

 



动态加载js和css

标签:append   tee   sso   tty   get   div   代码   css样式   tno   

原文地址:https://www.cnblogs.com/jzgd/p/8318337.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!