强制jQuery在页面加载完成后运行?

问题描述:

所以我有一个小的jQuery脚本,可以根据背景图像的宽高比调整元素大小。在某些情况下,它不能及时工作,我相信这是因为代码在图像完成下载之前运行。

So I have a small jQuery script that resizes elements according to their background image's aspect ratio. In certain instances, it doesn't work in time, and I believe this is because the code runs before the images finish downloading.

基本上,我有< div> 具有特定大小的背景图像的元素,我希望元素的大小完全相同。如果有一个比JS更好的方式,我会全力以赴。

Basically, I have <div> elements that will have a certain sized background image, and I want the element to be the exact same size. If there is a better way than with JS, I'm all ears.

我可以手动设置延迟,但有没有办法只在图像完成下载后运行代码?

I can manually set a delay, but is there a way to ONLY run the code after the images finish downloading?

我目前在 $(文件).ready(function(){...}); 里面有我的页脚。

I currently have it in $(document).ready(function(){...}); inside my footer.

请尝试

    $(window).on("load", function() {
       // your logic here.
    });

而不是

    $(document).ready(function(){...});

注意 - 在加载所有资产(包括图像)时调用load。当DOM准备好进行交互时,就会触发就绪。

Note - load is called when all assets are done loading, including images. ready is fired when the DOM is ready for interaction.