我正在使用 jquery.load 从另一个页面中提取 html 片段。该片段包含相当大的背景图像。一旦加载函数完成并调用它的回调,我将片段设置为在页面中显示 block - 问题是当 html 加载时我看到没有背景图像的新内容......背景图像稍后加载。
在显示 ajax 内容之前确保图像已加载的好方法是什么?
最佳答案
你可以这样做......
$('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 .
关于javascript - 当我显示 ajax 内容时图像未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4984181/