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' 

  • 相关阅读:
    错误 1324。文件夹路径 .. 中含有无效的字符
    linux下 tar解压 gz解压 bz2等各种解压文件使用方法
    取消EXCEL 2007/2010中邮箱地址的自动链接
    Windows2000/XP启动过程详解
    Ubuntu下安装apache2,mysql,php,wordpress.
    offcie2007,2010,2012中快速删除指定的页面.
    mysql连接,修改密码,增加用户,显示,导入导出
    键盘各按键的使用
    cvim 使用
    matlab基础知识(basic operation)
  • 原文地址:https://www.cnblogs.com/lr-blog/p/5512951.html
Copyright © 2011-2022 走看看