JS动态加载CSS和JS

这两天工作时用到动态加载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'