Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a jQuery function after all and any other javascript has run

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

like image 936
andy Avatar asked Jun 23 '10 01:06

andy


2 Answers

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.
   );
});
like image 164
Nick Craver Avatar answered Sep 25 '22 19:09

Nick Craver


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)

like image 45
Dan Heberden Avatar answered Sep 22 '22 19:09

Dan Heberden