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

JavaScript012

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

正常加载不是异步加载,但可以设置异步加载。

1、正常加载是指:

js在html里引用,即用script标签引入,不加script的其他属性设置。

2、可以设置是指:

1) defer,只支持IE

示例:

代码如下:

<script type="text/javascript" defer="defer">

alert(document.getElementById("miao").firstChild.nodeValue)

</script>

2) async :

async的定义和用法(是HTML5的属性)

async 属性规定一旦脚本可用,则会异步执行。

示例:

代码如下:

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

3) 创建script,插入到DOM中 ,加载完毕后callBack,见代码:

代码如下:

function loadScript(url, callback){

var script = document.createElement_x("script")

script.type = "text/javascript"

if (script.readyState){ //IE

script.onreadystatechange = function(){

if (script.readyState == "loaded" ||

script.readyState == "complete"){

script.onreadystatechange = null

callback()

}

}

} else {

script.onload = function(){

callback()

}

}

script.src = url

document.body.appendChild(script)

}