js异步加载的方式有哪些?

JavaScript011

js异步加载的方式有哪些?,第1张

方法一:Script Dom Element

(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)

})()

方法二:onload时的异步加载

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)

}

})()

方法三:$(document).ready()

在script标签中使用async

但是不能控制加载顺序 推荐RequireJS

<script type="text/javascript" src="demo_async.js" async="async"></script>

源码地址: https://github.com/getify/LABjs

实现方式: