j-dexx
j-dexx

Reputation: 10406

Difference between Jquery $(window).load vs window.onload

I have the following code:

function initialize() {
  var mapOptions = {
    center: new google.maps.LatLng(53.743317, -0.331004),
    zoom: 12
  };
  var map = new google.maps.Map(document.getElementById("map-canvas"),  mapOptions);
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?key={APIKEY}&sensor=false&callback=initialize';
  document.body.appendChild(script);
}

If I put

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

It won't load my map. Error in google maps js is Uncaught TypeError: Object #<Object> has no method 'Load'. However if I use

window.onload = loadScript;

It will load it in fine. I have absolutely no idea why.

$(window).load(loadScript());

Also works, just having it as a function that calls it doesn't. Could you tell me the reason of this behavior?

Upvotes: 1

Views: 2704

Answers (3)

Rajendraseo Pandey
Rajendraseo Pandey

Reputation: 1

The $(window).load execute when all DOM is ready including images. That means if our web page has completely loaded including image then $(window).load function will call.

$(window).load(function() {

 // script

})

for more detail about $(document).ready vs $(window).load vs window.onload click on

http://www.delhincrjob.com/blog/what-is-document-ready-vs-window-load-vs-window-onload/

Upvotes: -1

Alnitak
Alnitak

Reputation: 339776

You haven't actually invoked loadScript in the $(window).load() version - you've just created a "void" expression that evaluates to a reference to that function.

Do either:

$(window).load(function() {
     loadScript();  // NB: parentheses
})

or:

$(window).load(loadScript);

That said, you perhaps want $(document).ready() rather than $(window).load()

Upvotes: 2

CodeCarvings
CodeCarvings

Reputation: 324

in your jquery script you don't invoke the loadScript method... Use:

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

Upvotes: 0

Related Questions