JS异步加载的方式

方法一:Script Dom Element

1 2 3 4 5 6 7 8 (function(){      var scriptEle = document.createElement("script");      scriptEle.type = "text/javasctipt";      scriptEle.async = true;      scriptEle.src = "http://cdn.bootcss.com/jquery/3.0.0-beta1/jquery.min.js";      var x = document.getElementsByTagName("head")[0];      x.insertBefore(scriptEle, x.firstChild);          })();

  

<async>属性是HTML5中新增的异步支持。此方法被称为Script DOM Element方法

1 2 3 4 5 6 7 8 (function(){;      var ga = document.createElement(‘script‘);      ga.type = ‘text/javascript‘;      ga.async = true;      ga.src = (‘https:‘ == document.location.protocol ? ‘https://ssl‘ : ‘http://www‘) + ‘.google-analytics.com/ga.js‘;      var s = document.getElementsByTagName(‘script‘)[0];      s.parentNode.insertBefore(ga, s); })();

  

但是这种加载方式执行完之前会阻止onload事件的触发,而现在很多页面的代码都在onload时还执行额外的渲染工作,所以还是会阻塞部分页面的初始化处理。   方法二:onload时的异步加载

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 (function(){      if(window.attachEvent){          window.attachEvent("load", asyncLoad);      }else{          window.addEventListener("load", asyncLoad);      }      var asyncLoad = function(){          var ga = document.createElement(‘script‘);           ga.type = ‘text/javascript‘;          ga.async = true;          ga.src = (‘https:‘ == document.location.protocol ? ‘https://ssl‘ : ‘http://www‘) + ‘.google-analytics.com/ga.js‘;          var s = document.getElementsByTagName(‘script‘)[0];          s.parentNode.insertBefore(ga, s);      } })();

  

这种方法只是把插入script的方法放在一个函数里面,然后放在window的onload方法里面执行,这样就解决了阻塞onload事件触发的问题。 注:DOMContentLoaded与load的区别。前者是在document已经解析完成,页面中的dom元素可用,但是页面中的图片,视频,音频等资源未加载完,作用同jQuery中的ready事件;后者的区别在于页面所有资源全部加载完毕。   方法三:$(document).ready() 需要引入jquery,兼容所有浏览器  

1 2 3 $(document).ready(function() {       alert("加载完成!");   });

  

  方法四:<script>标签的async="async"属性

  • async属性是HTML5新增属性,需要Chrome、FireFox、IE9+浏览器支持
  • async属性规定一旦脚本可用,则会异步执行
  • async属性仅适用于外部脚本
  • 此方法不能保证脚本按顺序执行
  • 他们将在onload事件之前完成
1 < script  type="text/javascript" src="xxx.js" async="async"></ script >

  

方法五:<script>标签的defer="defer"属性

  • defer属性规定是否对脚本执行进行延迟,直到页面加载为止
  • 如果脚本不会改变文档的内容,可将defer属性加入到<script>标签中,以便加快处理文档的速度
  • 兼容所有浏览器
  • 此方法可以确保所有设置了defer属性的脚本按顺序执行
1 < script  type="text/javascript" defer></ script >

  

方法六:es6模块type="module"属性 浏览器对于带有type=”module”的<script>,都是异步加载,不会造成堵塞浏览器,即等到整个页面渲染完,再执行模块脚本,等同于打开了<script>标签的defer属性 。如下:  

1 < script  type="module" src="XXX.js"></ script >

  

ES6模块允许内嵌在网页中,语法行为与加载外部脚本一致,如下:

1 2 3 4 < script  type="module">     import utils from "./utils.js";     // other code </ script >

相关文章