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

JS动态加载CSS和JS

时间:2016-05-20 19:02:05      阅读:186      评论:0      收藏:0      [点我收藏+]

标签:

这两天工作时用到动态加载CSS和JS的地方比较多,这里稍微做下整理。

 

 

 

var tool = {
 loadStyle:function(url){
  var head = document.getElementsByTagName(‘head‘)[0] ,  //获取头标签
  link = document.createElement(‘link‘);            //创建link标签
  head.appendChild(link);                   //头标签里添加LINK标签
  link.href = url;                       //设置LINK的地址
  link.rel = ‘stylesheet‘;
},
loadScript:function(url, fn) {
var head = document.getElementsByTagName(‘head‘)[0] ,
script = document.createElement(‘script‘);
head.appendChild(script);
script.src = url;
script.charset = ‘utf-8‘;
script.onload = script.onreadystatechange = function() {
if (!this.readyState || this.readyState === ‘loaded‘ || this.readystate === ‘complete‘) {  //此处代码的解释在下面
if (fn) {
fn();
}
script.onload = script.onreadystatechange = null;
}
};
}
};

if (!this.readyState || this.readyState === ‘loaded‘ || this.readystate === ‘complete‘)

IF里面的表达式较多,在做这块的时候,在网上查了相关资料,觉得下面的解释比较合理:

因为在ie中使用onreadystatechange, 而gecko,webkit 浏览器和opera都支持onload。事实上this.readyState == ‘complete‘并不能工作的很好,理论上状态的变化是如下步骤: 
0 uninitialized 
1 loading 
2 loaded 
3 interactive 
4 complete 
但是有些状态会被跳过。根据经验在ie7中,只能获得loaded和completed中的一个,不能都出现,原因也许是对判断是不是从cache中读取影响了状态的变化,也可能是其他原因。最好把判断条件改成this.readyState == ‘loaded‘ || this.readyState == ‘complete‘ 

JS动态加载CSS和JS

标签:

原文地址:http://www.cnblogs.com/lr-blog/p/5512951.html

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