简体   繁体   English

加载图像时使用 jQuery .load 函数

[英]Using jQuery .load function when images are loaded

I'm wanting to use the jQuery .load function to run some code when all the images are loaded on the page.我想使用 jQuery .load函数在页面上加载所有图像时运行一些代码。

jQuery("img").load(function () {
    //run some code
});

Now the code runs but my question is, will the code run after all images on the page are loaded or will the code run when the first image element is loaded.现在代码运行,但我的问题是,代码会在页面上的所有图像加载后运行还是在加载第一个图像元素时运行。

I know I can use the jQuery $(document).ready function or the `$(window).load function, but this will fire when everything is loaded.我知道我可以使用 jQuery $(document).ready函数或 `$(window).load 函数,但是这将在加载所有内容时触发。 I want the code to run when the image elements are loaded, and before all the scripts in the footer load.我希望代码在加载图像元素时运行,并且在页脚中的所有脚本加载之前运行。

Anyone care to share their expert opinion on the matter?有人愿意分享他们对此事的专家意见吗?

I guess you should use the load function with the window instead of img's:我想你应该在窗口中使用 load 函数而不是 img 的:

 $(window).on('load', function() { // makes sure the whole site is loaded console.log("Everything loaded"); })

EDIT: Here you have a working example of a preloader: https://codepen.io/niklausgerber/pen/MKrVdQ编辑:这里有一个预加载器的工作示例: https : //codepen.io/niklausgerber/pen/MKrVdQ

Instead of image use window to know if every elements of the page loaded completely.而不是图像使用窗口来了解页面的每个元素是否已完全加载。

JQUERY查询

$(window).on('load', function() { 
 // do this
});

or

$(window).load(function() { 
 // do this
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM