I have a photo gallery page hosted on a CMS (Squarespace) which has some of it's own scripts which load the thumbnails asynchronously.
The actual large images however are not preloaded, so I decided to add my own script into the mix to just make the browser load those larger images into the cache in the background, like this:
(function($) {
var cache = [];
// Arguments are image paths relative to the current page.
$.preLoadImages = function() {
var args_len = arguments.length;
for (var i = args_len; i--;) {
var cacheImage = document.createElement('img');
cacheImage.src = arguments[i];
cache.push(cacheImage);
}
}
})(jQuery)
$(window).load(function(){
$.preLoadImages(
"/picture/1.jpg",
"/picture/2.jpg", //etc.
);
});
I placed my code in a $(window).load() because this is a background script and it's not essential it even runs at all, it's just to improve performance.
However, I think this script is somehow blocking the CMS's own thumbnail preloading script.
Am I right? And most importantly, is there a way to dictate that my script only run after all other scripts on the page have run?
cheers
JavaScript is always running, the hover
event for example is firing constantly, mousemove
, etc...there's no "end" to the script run.
However in your case, this shouldn't block any other preloading...also you can use document.ready
here, since you don't actually need images loaded before your code executes.
In fact, you're actually slowing down the page by using window.load
instead...since the preloading starts later, when it could be parallelized with other downloads earlier by the browser. Instead use document.ready
, like this:
$(function(){
$.preLoadImages(
"/picture/1.jpg",
"/picture/2.jpg", //etc.
);
});
Scripts are loaded top down, and body onloads are normally appended to existing onloads - so as long as that $(function().. is at the end of the page, it'll be ran last. (last (as per nick's comment) meaning the initial parse/run of the document)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With