当服务器响应缓慢时,jQuery 在加载/就绪时不触发

jQuery not firing on load/ready when server responce is slow

本文关键字:就绪 加载 jQuery 响应 服务器 缓慢      更新时间:2023-09-26

我在jQuery(document).ready()和jQuery(window).load()上触发了一个函数。两者都是相同的功能。它应该触发图像大小调整脚本。

但是,有时,当服务器响应缓慢时,脚本在页面加载完成后根本不会触发。

我已经遇到这个问题很长一段时间了,也许这是矫枉过正,但是到目前为止,我在文档就绪和窗口加载中调用如下所示的函数:

    jQuery('img', '.background').each(function(){
        jQuery(this).load(function(){
            jQuery(this).resizeImage();
        });
    });

它调用的函数是:

jQuery.fn.resizeImage = function() {
console.log('fired');
var bgImg = jQuery(this);
/* get img sizes */
var imgwidth = bgImg.width();
var imgheight = bgImg.height();
/* get window sizes */
var winwidth = jQuery(window).width();
var winheight = jQuery(window).height();
/* get the ratio, checks wether window is bigger or smaller than the image */
var widthratio = winwidth / imgwidth;
var heightratio = winheight / imgheight;
/* checks the difference */
var widthdiff = heightratio * imgwidth;
var heightdiff = widthratio * imgheight;
/* if you want the entire image to always fit the screen, change the > to < */
if(heightdiff>winheight) { 
    bgImg.css({
        width: winwidth+'px',
        height: heightdiff+'px',
        marginLeft: '-'+winwidth/2+'px'
    });
} else {
    bgImg.css({
        width: widthdiff+'px',
        height: winheight+'px',
        marginLeft: '-'+widthdiff/2+'px'
    });     
}
};

使用控制台.log,我发现该函数根本不会触发。

谁能指出我正确的方向,为什么这可能不起作用?

猜猜你错过了使用this

   jQuery('img', '.background').each(function(){
        var $self = $(this);
        $self.load(function(){
            $self.resizeImage();
        });
    });

自己解决了。

问题出在以下几点:

jQuery(window).load(function(){
    jQuery('img', '.background').each(function(){
        jQuery(this).load(function(){
            jQuery(this).resizeImage();
        });
    });
});

由于双重加载(jQuery(window).load 和 jQuery(this).load),代码根本没有执行。由于加载窗口时,图像也已加载。