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


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.
   );
});

脚本从上到下加载,而body加载通常会附加到现有的onload上,所以只要$(function()..在页面末尾,它就会最后运行(最后(根据nick的评论)表示文档的初始分析/运行)

链接地址: http://www.djcxy.com/p/1430.html

上一篇: 使用Javascript检测特定的iPhone / iPod touch模型

下一篇: 如何运行一个jQuery函数和所有其他的JavaScript运行