Billa
Billa

Reputation: 2039

Why do we need the onload event?

I have a very basic code to load Bing maps. By placing this code in the head section of an HTML, it will load the map inside a div #map.

This will work fine:

<script type="text/javascript">
         window.onload = GetMap;               
         function GetMap()
         {
            map = new VEMap('map');
            map.LoadMap();            
         }
         </script>

As the above code simply loads the function GetMap. So shouldn't the code inside the function work without using function as well? For example:

<script type="text/javascript">
            map = new VEMap('map');
            map.LoadMap();
        </script>

But why this would not work?

Upvotes: 0

Views: 121

Answers (4)

socha23
socha23

Reputation: 10239

If you place it in the head section, it will execute before whole page is rendered and "map" div is created. This will cause errors when trying to change the div contents.

By wrapping it in function and calling that function on window load, you ensure that the code is executed only after page is fully rendered.

Alternatively you could just place your code after the div, then it should work.

Upvotes: 1

Roman
Roman

Reputation: 6408

long story short: If you don't like functions (WHAT DID THEY DO TO YOU?!), put that second script at the bottom of the body element

Upvotes: 1

James Hull
James Hull

Reputation: 3689

It doesn't work because the map element doesn't exist in the DOM when you call

map = new VEMap('map');

The window onload event fires at the end of the document loading process - so all objects in the document are in the DOM.

Upvotes: 1

JohnP
JohnP

Reputation: 50009

I'm assuming that Bing maps binds to a DOM element to show the map (just like Google maps). If that's the case that DOM element must first be loaded by the browser for the binding to work. Loading it on window.load ensures that this happens. I'm sure your code should work if you move it to the bottom of the page, just above the body tag.

Upvotes: 1

Related Questions