教你 Jsimport 如何实现 懒加载 和 预加载

JavaScript013

教你 Jsimport 如何实现 懒加载 和 预加载,第1张

在项目中引入 js 文件一般是如下这种模式:

懒加载:

当文件被需要时才被加载即 执行fn()时,多次执行fn()只会加载一次js文件

预加载:

文件会在浏览器空闲的时候提前加载,有兼容性问题需慎用

jquery预加载的两种方式说明如下:

1、通过写函数进行预加载

function preload(arrayOfImages) {

$(arrayOfImages).each(function(){

$('<img/>')[0].src = this//循环加载传进来的图片数组

})

}

调用方法:

preload([

'img/imageName.jpg', //图片1

'img/anotherOne.jpg',//图片2

'img/blahblahblah.jpg'//图片3

])

2、通过插件的方式预加载

//自定义函数preload,实现原理跟方法一差不多

$.fn.preload = function() {

this.each(function(){

$('<img/>')[0].src = this

})

}

调用方法:

$(['img1.jpg','img2.jpg','img3.jpg']).preload()

声音预加载,可以通过绕一下的方式去实现它,就是首先在头部构建你所需要加载的声音,然后添加对应的bgsound对象,让其同步加载,当声音全部加在完后,html回去执行window.onload动作,这个时候,声音已经在本地IE缓存中,然后在onload中删除预加载的bgsound对象,这样就是先了声音的预加载。

你在测试的时候可以先清空IE缓存,然后执行代码,再查看缓存。

代码如下:

<HTML>

<HEAD>

<TITLE>New Document </TITLE>

<bgsound volume='-5000' id='bgsound1' loop='1' src="http://localhost:8088/bpelDemo/aaa.mp3">

<bgsound volume='-5000' id='bgsound2' loop='1' src="http://localhost:8088/bpelDemo/bbb.mp3">

<bgsound volume='-5000' id='bgsound3' loop='1' src="http://localhost:8088/bpelDemo/ccc.mp3">

<bgsound volume='-5000' id='bgsound4' loop='1' src="http://localhost:8088/bpelDemo/ddd.mp3">

</HEAD>

<BODY>

<script>

function window.onload(){

var bgSoundObj = document.getElementById("bgsound1")

bgSoundObj.src=""

bgSoundObj.volume=1

//删除多余的bgsound对象

var bgSoundObjs = document.getElementsByTagName("bgsound")

for(var i=1i<bgSoundObjs.lengthi++){

bgSoundObjs[i].removeNode()

}

alert("目前所有音乐加载完成,可以去IE缓存查看加载MP3文件")

}

</script>

声音已经加载,播放无需重新加载<p>

<input type='button' onclick='document.getElementById("bgsound1").src="http://localhost:8088/bpelDemo/aaa.mp3"' value="music1">

<input type='button' onclick='document.getElementById("bgsound1").src="http://localhost:8088/bpelDemo/bbb.mp3"' value="music2">

<input type='button' onclick='document.getElementById("bgsound1").src="http://localhost:8088/bpelDemo/ccc.mp3"' value="music3">

<input type='button' onclick='document.getElementById("bgsound1").src="http://localhost:8088/bpelDemo/ddd.mp3"' value="music4">

</script>

</BODY>

</HTML>