js加载所有图片资源,加载完毕再进行后续动作。
JFunction.PreLoadData = function (url) { if (typeof url == 'undefined') { url = ''; } var loadedNum = 0;//已加载资源数量 var resourceNum = 0;//资源数量 var postAction = function () { };//资源加载完成后的回调函数 function imageLoadPost() {//每成功加载一个图片执行一次 loadedNum++; if (loadedNum >= resourceNum) {//全部图片文件加载完后,继续加载声音 loadedNum = 0; resourceNum = 0; loadAudio(); } } function audioLoadPost() {//每成功加载一个声音执行一次 loadedNum++; if (loadedNum >= resourceNum) {//全部声音文件加载完后,执行回调函数 postAction(); } } function loadImage() {//加载图片 for (var m2 in ResourceData.Images) resourceNum++; if (resourceNum == 0) { imageLoadPost(); } else { for (var m2 in ResourceData.Images) { ResourceData.Images[m2].data = new Image(); ResourceData.Images[m2].data.src = url + ResourceData.Images[m2].path; ResourceData.Images[m2].data.onload = function () { imageLoadPost(); } ResourceData.Images[m2].data.onerror = function () { alert('图片资源 ' + ResourceData.Images[m2].data.src + ' 加载失败!'); return; } } } } function loadAudio() {//加载声音 for (var m1 in ResourceData.Sound) resourceNum++; if (resourceNum == 0) { audioLoadPost(); } else { for (var m1 in ResourceData.Sound) { ResourceData.Sound[m1].data = new Audio(); var playMsg = ResourceData.Sound[m1].data.canPlayType('video/ogg');//测试浏览器是否支持该格式声音 if ("" != playMsg) { ResourceData.Sound[m1].data.src = url + ResourceData.Sound[m1].path; } else { ResourceData.Sound[m1].data.src = url + ResourceData.Sound[m1].path; } ResourceData.Sound[m1].data.addEventListener("canplaythrough", function () { audioLoadPost(); }, false); ResourceData.Sound[m1].data.addEventListener("error", function () { alert('声音资源 ' + url + ResourceData.Sound[m1].path + ' 加载失败!'); return; }, false); } } } loadImage(); return { done: function (f) { if (f) postAction = f; } } };