zoukankan      html  css  js  c++  java
  • 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' 

  • 相关阅读:
    Apply SOA Design Patterns with WCF (1) Configuration Centralization (配置集中管理)
    NBearLite PetShop 4.0示例源码
    发布NBearLite中文版完全参考手册 + NBearLite 10分钟入门教程 + NBearLite v1.0.0.7 beta
    NBear WebTest 分享一个基于Web的UnitTest工具
    Linux的rsh配置rhost
    [SCM]源码管理 perforce label实例
    python面试题
    LinuxTips目录下的所有的子目录
    perlcgi基础
    perlcgi命令行调试
  • 原文地址:https://www.cnblogs.com/lr-blog/p/5512951.html
Copyright © 2011-2022 走看看