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?
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.