当服务器响应缓慢时,jQuery 在加载/就绪时不触发
jQuery not firing on load/ready when server responce is slow
我在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),代码根本没有执行。由于加载窗口时,图像也已加载。
相关文章:
- Ajax请求文档就绪会导致jquery加载缓慢
- 在页面上加载高级jQuery版本准备就绪
- 事件侦听器更新就绪在加载时未显示确认,而更新实际存在
- jQuery表单在就绪/加载时不起作用
- 在jquery循环幻灯片中使用加载函数而不是就绪函数
- DOM解析,加载,渲染,就绪有什么区别
- 文档就绪功能 - 不先加载代码
- 在 dashshing Widget 的 coffeescript 中加载“就绪”的数据
- 在页面加载之前捕获点击事件,并在 DOM 准备就绪后触发
- 如何在尚未准备就绪时显示“加载”
- 加载 HTML 页面和脚本后的 AJAX 就绪事件
- jquery文档就绪侦听器与图像加载;执行顺序
- 当服务器响应缓慢时,jQuery 在加载/就绪时不触发
- Jquery 依赖下拉列表以加载到文档就绪
- 角度单页应用程序,videoJS就绪功能仅在页面加载时触发
- 当 DOM 准备就绪时,使用 js 加载引导选项卡代码
- 科尔多瓦 + 主干网.js - 延迟主.js加载,直到触发设备就绪
- 在加载和就绪事件之前,将图像大小获取到全局变量中
- 在jquery就绪后,在_layout视图中,当页面加载时,从子视图自动调用javascript函数
- 页面加载准备就绪时加载选项卡中的内容