我正在使用这个脚本......
它将URL中特定#id的内容加载到当前页面,并为其设置动画...从页面侧面滑动...当用户点击链接时
一切正常,除了图片需要时间加载......我尝试并努力将图像预加载器合并到此?所以所有内容都加载在一起
function goTo(href) {
var left = $(window).width();
$('#id').css("left", left);
$.ajax({
url: href,
success: function (data) {
var content = $(data).find('#id').html();
// Windows Load Function
$(window).load(function () {
$("#id").html(content).animate({
left: '0',
}, 'fast');
var title = $('#id').find('h1').text();
$('head').find('title').text(title);
});
}
});
}
// check for support before we move ahead
if (typeof history.pushState !== "undefined") {
var historyCount = 0;
// On click of link Load content and animate
$('.access a').live('click', function () {
var href = $(this).attr('href');
goTo(href);
history.pushState(null, null, href);
return false;
});
window.onpopstate = function () {
if (historyCount) {
goTo(document.location);
}
historyCount = historyCount + 1;
};
}
答案 0 :(得分:5)
窗口加载事件只发生一次。您要做的是将内容解析为html片段,循环并预加载图像,然后附加内容。
// this contains the content we want to append
var $content = $(data).find('#id').children();
// these are the images that are in content that we need to preload
var $images = $content.find("img").add($content.filter("img"));
// keep track of successfully preloaded images
var counter = 0;
// deferred object that will resolve when all images are preloaded
var $def = $.Deferred();
$images.each(function(){
// if image is already loaded, increment counter and move on.
if (this.complete || this.readystate === 4) {
counter++;
// if all images are preloaded, resolve deferred object
if (counter === $images.length) $def.resolve();
}
else {
// since the image isn't already preloaded, bind the load event.
$(this).load(function(){
counter++;
// if all images are preloaded, resolve deferred object
if (counter === $images.length) $def.resolve();
});
}
});
// when done preloading, this function will happen.
$def.done(function(){
// empty target element and append content to it, then animate it.
$("#id").empty().append($content)
.animate({
left: '0'
}, 'fast');
var title = $('#id').find('h1').text();
$('head').find('title').text(title);
});
答案 1 :(得分:0)
您必须事先知道可能出现的图像。然后,您必须将这样的内容添加到HTML正文中:
<div id="img-preloader">
<p>If you're seeing a crapton of images here, that's a bug. Just ignore them.</p>
<!-- No "display:none" because some browsers completely ignore this then -->
<img alt='' src="some/image.jpg" />
<img alt='' src="another_image.png" />
<img alt='' src="img78236.bmp" />
<img alt='' src="img046502.jpg" />
<img alt='' src="DCIM732065230.jpg" />
<img alt='' src="DCIM478346935.jpg" />
<!-- all the images here are those that you have to preload -->
</div>
<style type="text/css">
#img-preloader *{height:0; width:0; opacity:0;}
#img-preloader {margin-left:-6543467624px;position:absolute;
visibility:hidden;height:0;width:0;opacity:0}
</style>
你只能用你知道可以在那里出现的图像来做这件事,因为没有办法预测你应该预先加载哪些图像。此外,如果有很多图像我根本不建议预加载,因为它会减慢初始页面加载速度。