Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $(window).load not working as expected

I ran into an something that did not expect today when removing part of a function that previously was loaded in my asset pipeline but needed to be extracted to a partial for some A/B testing.

I'm using the bigVideo.js library to load a full-screen video on the page. BigVideo.js started loading the wrong dimensions today when I extracted the code to the partial. The partial loads below the rest of my javascript assets.

I previously had the code incapsulated in a anonymous function inside my normal asset pipeline.

original code (working)

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

Next, I tried to set this equal variable so I could call it in the partial. Video started loading without using correct dimensions.

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

in partial:

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

It looked like something was going on with the dom dimensions not fully loading, so I tried switching the function to something like this:

in partial:

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

Still no luck.

Finally, I resorted to using window.onload

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

It works?! So why is $(window).load failing here while window.onload seems to be working fine?

like image 634
Paul Avatar asked May 13 '13 07:05

Paul


1 Answers

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.

like image 61
Vadim Avatar answered Sep 27 '22 23:09

Vadim