zoukankan      html  css  js  c++  java
  • 动态加载script文件 专题

    动态加载script到页面大约有俩方法

    第一种就是利用ajax方式,把script文件代码从后台加载到前台,然后对加载到的内容通过eval()执行代码。第二种是,动态创建一个script标签,设置其src属性,通过把script标签插入到页面head来加载js,相当于在head中写了一个<script src="..."></script>,只不过这个script标签是用js动态创建的
    比如说是我们要动态地加载一个callbakc.js,我们就需要这样一个script标签:
    <script type="text/javascript" src="call.js"></script>


    如下代码就是如何通过js来创建这个标签(并且加到head中):
     
    var head= document.getElementsByTagName('head')[0];  
    var script= document.createElement('script');  
    script.type= 'text/javascript';  
    script.src= 'call.js';  
    head.appendChild(script);

    当加载完call.js, 我们就要调用其中的方法。不过在header.appendChild(script)之后我们不能马上调用其中的js。因为浏览器是异步加载这个js的,我们不知道他什么时候加载完。然而我们可以通过监听事件的办法来判断helper.js是否加载完成。(假设call.js中有一个callback方法)

     
    var head= document.getElementsByTagName('head')[0]; 
    var script= document.createElement('script'); 
    script.type= 'text/javascript'; 
    script.onreadystatechange= function () { 
         if (this.readyState == 'complete')
         callback(); 
       }    
    script.onload= function(){ 
        callback();
     } 
    script.src= 'helper.js'; 
    head.appendChild(script);  

     我设了2个事件监听函数, 因为在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'


    参考jQuery的实现我们最后实现为:

     
    var head= document.getElementsByTagName('head')[0]; 
    var script= document.createElement('script'); 
    script.type= 'text/javascript'; 
    script.onload = script.onreadystatechange = function() { 
        if (!this.readyState || this.readyState === "loaded" ||    this.readyState === "complete" ) {
            help(); 
            // Handle memory leak in IE
                script.onload = script.onreadystatechange = null; 
        } }; 
    script.src= 'helper.js'; 
    head.appendChild(script); 
     
     还有一种简单的情况就是可以把help()的调用写在helper.js的最后,那么可以保证在helper.js在加载完后能自动调用help(),当然最后还要能这样是不是适合你的应用。


    另外需要注意:
    1.因为script标签的src可以跨域访问资源,所以这种方法可以模拟ajax,解决ajax跨域访问的问题。
    2.如果用ajax返回的html代码中包含script,则直接用innerHTML插入到dom中是不能使html中的script起作用的。粗略的看了下jQuery().html(html)的原代码,jQuery也是先解析传入的参数,剥离其中的script代码,动态创建script标签,所用jQuery的html方法添加进dom的html如果包含script是可以执行的。如:

    jQuery("#content").html("<script>alert('aa');<\/script>");

  • 相关阅读:
    关于xml的使用。
    Input标签文件上传,使用详解
    webpack 集成 Typescript && Less
    ionic3 多级联动城市选择插件 ion-multi-picker
    ionic2(3) 密码键盘组件 ionic2-pincode-input 使用
    ionic3 图片(轮播)预览 ionic-gallary-modal组件使用方法
    ios打包,通过Xcode生成ipa文件
    php常见的验证方法
    php 时间转化为刚刚、几秒前、几分前、几天前等等,友好时间提示
    ionic node-sass安装或编译失败:MSBUILD : error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”
  • 原文地址:https://www.cnblogs.com/skykang/p/2112685.html
Copyright © 2011-2022 走看看