10

我今天在删除以前加载到我的资产管道中但需要提取到部分进行 A/B 测试的部分功能时遇到了今天没有预料到的事情。

我正在使用 bigVideo.js 库在页面上加载全屏视频。今天,当我将代码提取到部分时,BigVideo.js 开始加载错误的尺寸。我的其余 javascript 资产下方的部分负载。

我之前将代码封装在我的正常资产管道中的匿名函数中。

原始代码(工作)

$(function () {
  (function () {
  var bgVid = new $.BigVideo({useFlashForFirefox: false})
  bgVid.show('http://videourl.com', { ambient : true });
  }();
});

接下来,我尝试设置这个相等的变量,以便我可以在部分中调用它。视频开始加载时没有使用正确的尺寸。

$(function () {
  var initVid = function () {
  var bgVid = new $.BigVideo({useFlashForFirefox: false})
  bgVid.show('http://videourl.com', { ambient : true });
  };

部分:

$(function () {
  initVid();
});

看起来 dom 尺寸没有完全加载时发生了一些事情,所以我尝试将函数切换为如下所示:

部分:

$(window).load(function () {
  var bgVid = new $.BigVideo({useFlashForFirefox: false});
  bgVid.show('http://videourl.com', { ambient : true });
});

仍然没有运气。

最后,我求助于使用 window.onload

window.onload = function () {
  var bgVid = new $.BigVideo({useFlashForFirefox: false})
  bgVid.show('http://videourl.com', { ambient : true });
};

有用?!那么为什么 $(window).load 在这里失败,而 window.onload 似乎工作正常?

4

1 回答 1

17

There are several different events you can use in order to be sure DOM is ready:

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

is the same as

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

and is executed when HTML document is loaded. From the other hand you can use

$(window).load(function() { ... });

which is deprecated equivalent of

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

which happens later, when not only HTML document is loaded, but also all linked resources like images and styles as well. More about the differences you can read here.

For modern browsers there is also an option to use document.ondomcontentready which is equivalent to non-standard document.ready added by jQuery.

As for me, I prefer not to mess with incompatibility of different browsers behavior and events support once I have tools like jQuery in my hand. Just use $(function(){...}) and don't think twice.

于 2013-05-13T08:00:33.530 回答