I have a page with a few popups showing the details of each item on the page. When the user clicks on a button, the popup (which is a jQuery dialog) is shown. The html of the dialog is pulled from another page/url. I use jQuery's .load() method. The browser takes a couple of seconds the first time a page is loaded into my dialog, something that my boss doesn't want.
I've tried to preload these pages asynchronously, but I can't get it to work. The page gets blocked until all the loading happens. I've tried it three different ways:
//1
$('.transactions-preloader').each(
function(index, Element){
var id = Element.id.replace('details-dialog', '');
$(this).load( "/" + id + "/1/" + period + ".html" );
}
);
//2
$('.transactions-preloader').each(
function(index, Element){
var id = Element.id.replace('details-dialog', '');
$.ajax({
url: "/" + id + "/1/" + period + ".html",
async: true,
cache: false,
success: function(html){
$("#"+Element.id).html(html);
}
});
}
);
//3
$('.transactions-preloader').each(
function(index, Element){
var id = Element.id.replace('details-dialog', '');
$.get( "/" + id + "/1/" + period + ".html", function(data) {
$("#"+Element.id).html(data);
});
}
);
The three ways work fine, except that they all block the page while the load is happening.
Any ideas on开发者_如何学运维 how to do asynchronously preloading?
Try this it will not hang the browser.
$('.transactions-preloader').each(
function(index, Element){
setTimeout(function(){
var id = Element.id.replace('details-dialog', '');
$(this).load( "/" + id + "/1/" + period + ".html" );
}
}, 10);
);
If you know the paths of the files, a classic pre-loader script might be useful:
var loadImages = (function() {
var imageArray = [];
// imagePaths is an array of image paths
return function(imagePaths) {
var i = imagePaths.length;
var image;
while (i--) {
image = new Image();
image.src = imagePaths[i];
imageArray.push(image);
}
}
}());
Whenever you load a new part of the page, pass the image paths in an array to the function. You can clear out the imageArray each time if you want, once the images are loaded they don't need to stay in the array, but they have to hang around long enough to be loaded.
try
$(window).load(function() {
// preloading code
})
this will call the preload after your page (including all frames, images, etc) loaded.
note that this is jquery load event handler, not load function
精彩评论