源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

理解Javascript文件动态加载

  • 时间:2022-07-08 05:54 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:理解Javascript文件动态加载
Javascript文件动态加载一直是比较困扰的一件事情,像网络上传的比较常见的做法:
function loadjs(fileurl){
 var sct = document.createElement("script");
 sct.src = fileurl;
 document.head.appendChild(sct);
}
然后我们来测试一下结果:
<html>
  <head>
   <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" media="screen" />
  </head>
  <body>
    <script>
    function loadjs(fileurl){      
     var sct = document.createElement("script");
     sct.src = fileurl;
     document.head.appendChild(sct);
    }
    loadjs("http://code.jquery.com/jquery-1.12.0.js");
    loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js")
    
    loadjs("http://bootboxjs.com/bootbox.js")
    </script>
  </body>
</html>
代码加载完后,会出现下图的错误: [img]http://files.jb51.net/file_images/article/201601/2016129144529945.jpg?2016029144540[/img] [b]jquery明明是加载在第一个处理,为什么还是报jQuery不存在的对象呢? [/b] 因为这样加载,相当于开启了三个线程,只是jquery这个文件先启动线程,而jquery执行完这个线程的时间,超过了后面两个时间. 因此后面执行完的,可能没能找到jquery这个对象。 [b]然这种方式怎么处理呢? [/b] 其实文件的加载是有个状态处理的.文件的加载有个onload事件,就是可以监听文件是否加载完成的事件. 因此我们可以考虑这个方法来处理我们想要的结果.我们用直观的方式来处理.改进后的代码如下:
 <html>
  <head>
   <link rel="stylesheet" type="text/css" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" media="screen" />
  </head>
  <body>
    <script>
    
    function loadjs(fileurl, fn){      
     var sct = document.createElement("script");
     sct.src = fileurl;
     if(fn){
      sct.onload = fn;
     }
     document.head.appendChild(sct);
    }


    loadjs("http://code.jquery.com/jquery-1.12.0.js",function(){
     loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js",function(){
        loadjs("http://bootboxjs.com/bootbox.js")
     })
    });
      
    
    </script>
  </body>
</html>

OK,执行完这个代码之后,加载文件都是在前一个加载完成后,才会加载另外一个,这样就不会造成找不到用到的对象了. 然后我们来执行一个弹出框的效果,代码里面使用了 Bootbox.js 插件. 加载代码如下:
loadjs("http://code.jquery.com/jquery-1.12.0.js",function(){
  loadjs("http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js",function(){
       loadjs("http://bootboxjs.com/bootbox.js",function(){
          bootbox.alert("Hello world!", function() {
           Example.show("Hello world callback");
          });
       })
   })
 });
刷新页面,就会直接显示弹出框: [img]http://files.jb51.net/file_images/article/201601/2016129144558826.jpg?201602914467[/img] 动态加载的代码,往往容易在这里花费很多时间调试.大家最好的办法就是写一个最简单的例子,理解其中的原因. 这里的代码都可以进行封装,还可以加入CSS文件的加载.作为自己的插件使用。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部