2011-02-13 77 views
1

我正在使用jquery.load從另一個頁面拉入html片段。該片段包含相當大的背景圖像。一旦加載函數完成並調用它的回調函數,我將片段設置爲在頁面中顯示塊 - 問題在於,當加載html時,我看到沒有背景圖像的新內容....稍後加載背景圖像。當我顯示ajax內容時未加載圖像

在顯示ajax內容之前確保圖像加載的最佳方法是什麼?

+0

您可以向我們展示您目前爲止的一些代碼;可能會更容易回答。 – miku 2011-02-13 12:45:36

+0

向我們顯示您的源代碼。 – KomarSerjio 2011-02-13 12:48:16

回答

3

你可以這樣做......

$('button').click(function() { 
    $('#element').load('/echo/html/', function(responseText) { 

     // For testing 
     responseText = '<link href="http://sstatic.net/stackoverflow/all.css?v=ded66dc6482e" rel="stylesheet" type="text/css" /><div class="ac_loading" style="width: 200px; height: 200px;">ABC</div>'; 


     var element = $(this), 
      responseTemp = $('<div />').hide().html(responseText).appendTo('body'), 
      styles = responseTemp.find('link[type="text/css"]'), 
      stylesHook = $('head link[type="text/css"]:last'); 

     if (stylesHook.length === 0) { 
      stylesHook = $('head *:last-child'); 
     } 

     styles.insertAfter(stylesHook); 

     preloadSrc = responseTemp.find('div').css('backgroundImage').replace(/^url\(["']?(.*?)["']?\)$/, '$1'), image = new Image(); 

     image.onload = function() { 
      styles.add(responseTemp).remove(); 
      element.html(responseText); 
     } 

     image.src = preloadSrc; 
    }); 
}); 

jsFiddle

相關問題