2011-02-13 31 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

相关问题