基本上我想知道當整個文件完成下載時,jQuery的$ .get()方法的'成功函數'是否被觸發。我懷疑這是,但只是想確保。
我使用一系列$ .get()請求來加載頁面(CSS,javascript等)的文件,同時我顯示一個'加載屏幕'。
在請求的每次成功回調中,我加載下一個文件,直到它們全部完成,然後刪除我的加載屏幕。
問題是,隨機,通常在慢速連接(網站是專爲移動瀏覽)加載屏幕將消失,但該網站的CSS沒有被應用,直到1-2秒後,所以用戶將看到一個非現場風格簡要之前CSS應用到按鈕等
這裏是我用來加載我的資源代碼
if(!window.MyResourceLoader) window.MyResourceLoader = {};
// list of resources to load
MyResourceLoader.MyResources = new Array(
"include/resources/.....css",
"include/resources/.....css",
"include/modules/.......js",
"include/...............js",
"include/...............js");
// reverse the array so we load it in the order above
MyResourceLoader.MyResources.reverse();
MyResourceLoader.resourcesToLoad = MyResourceLoader.MyResources.length;
/**
* Recursive function - loads the resources
*/
MyResourceLoader.loadMyResources = function()
{
// exit condition - stop recurring if we've run out of resources to load
if(this.MyResources.length < 1)
{
$(".meter > span").each(function() {
$(this).stop().animate({
width: "100%"
}, 300);
});
return;
}
// get the next resource to load
var resource = this.MyResources.pop();
// if the resource is a css file, append it to the head
if(resource.match(/css$/))
{
// append timestamp to resource
resource += ("?" + new Date().getTime());
// ie support
if(document.createStyleSheet)
document.createStyleSheet(resource);
else
$("head").append($('<link type="text/css" rel="stylesheet" href="' + resource + '">'));
// recusivley load resources
this.loadMyResources();
}
else if(resource.match(/\.js$/))
{
// append timestamp to resource
resource += ("?" + new Date().getTime());
// if the resource is a js file, make a request for it
$.get(resource, function()
{
// on successful request of the file, make another call to load resource
MyResourceLoader.loadMyResources();
});
}
}
最終的JavaScript文件是一個「負載端」的.js文件做以下操作:
// fade out the loading screen
$('#webapp-loader').css('opacity',0);
setTimeout(function()
{
$('#webapp-loader').remove();
}, 1000);
正如你所看到的那樣,在加載結束之前,甚至會有1秒的緩衝區,然後它將刪除加載屏幕。
只是重新閱讀代碼,我想我找到了我的問題:) - 資源加載只追加CSS文件到文件的頭部,這會觸發CSS的下載文件 - 所以上面的代碼不會等待頭部的CSS完成下載之前,它認爲它是'完成加載' – jenovachild 2013-05-13 01:32:51