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' 

  • 相关阅读:
    结对编程队友个人项目分析
    Android入门3:从Toolbar到Material Design
    Qt串口通信
    AVT Vimba与OpenCV环境配置
    Git远程使用技巧
    Android入门2:从GridView控件使用到自定义Adapter
    Android入门1:使用VideoView和MediController播放视频
    kafka+spark streaming+redis学习
    kafka学习笔记
    安卓获取服务器返回的图片资源路径并下载图片
  • 原文地址:https://www.cnblogs.com/lr-blog/p/5512951.html
Copyright © 2011-2022 走看看