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

JavaScript08

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

首先引用jquery.scrollLoading.js(上一篇博文有)和jquery.js

把下面代码放到标签里,就会得到异步加载图片的效果

//这个在我上一篇博文有这个

$(document).ready(function () {

//实现图片慢慢浮现出来的效果

$("img").load(function () {

//图片默认隐藏

$(this).hide()

//使用fadeIn特效

$(this).fadeIn("5000")

})

// 异步加载图片,实现逐屏加载图片

$(".scrollLoading").scrollLoading()

})

注意img里的class,在这里就不细说了

data-url表示将要异步加载的图片,src表示首先加载的图片(一般会是小图片,或者是一个动画,网页中全部的src链接同一个图片,这样网页就加载快好多,这个时候再异步的加载要加载的图片,也就现在要说的功能)

<img class="scrollLoading" data-url="image/logo.jpg" src="/Images/120.gif" />