开发者

how to use window.onload?

I'm refactoring a website using MVC. What was a set of huge pages with javascript, php, html etc etc is becoming a series of controllers and views. I'm trying to do it in a modular way so views are split in 'modules' that I can reuse in other pages when needed

eg. "view/searchform displays only one div with the searchform "view/display_events displays a list of events and so on.

One of the old pages was supposed to load a google map with a marker on it.开发者_运维知识库

Amongst the rest of the code, I can identify the relevant bits as follows

<head>
<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key=blablabla" type="text/javascript"></script>

<script type="text/javascript">
//<![CDATA[
function load() {
    if (GBrowserIsCompatible()) {
        var map = new GMap2(document.getElementById("map"));
        var point = new GLatLng(<?php echo ($info->lat && $info->lng) ? $info->lat .",". $info->lng : "51.502759,-0.126171"; ?>);
        map.setCenter(new GLatLng(<?php echo ($info->lat && $info->lng) ? $info->lat .",". $info->lng : "51.502759,-0.126171"; ?>), 15);
        map.addControl(new GLargeMapControl());
        map.addControl(new GScaleControl());
        map.addOverlay(new GMarker(point));
        var marker = createMarker(point,GIcon(),"CIAO");
        map.addOverlay(marker);
    }
}
//]]>
</script>
</head>

...then

<body onload="load()" onunload="GUnload()">

...and finally this div where the map should be displayed

<div id="map" style="width: 440px; height: 300px"> </div>

Don't know much about js, but my understanding is that

a) I have to include the scripts in the view module I'm writing (directly in the HTML? I would prefer to load a separate script)

b) I have to trigger that function using the equivalent of body onload... (obviously there's no body tag in my view. In my ignorance I've tried div onload=.... but didn't seem to be working :)

What do you suggest I do? I've read about window.onload but don't know what's the correct syntax for that.

please keep in mind that other parts of the page include other js functions (eg, google adsense) that are called after the footer.


You can attach a handler to the window load event with js, so you don't need the markup.

// crossbrowser event binding from http://www.quirksmode.org/js/eventSimple.html
//function addEventSimple(obj,evt,fn) {
//    if (obj.addEventListener)
//      obj.addEventListener(evt,fn,false);
//    else if (obj.attachEvent)
//      obj.attachEvent('on'+evt,fn);
//}

// using Google API's event functions
GEvent.addDomListener(window, "load", load);
GEvent.addDomListener(window, "unload", GUnload);

function load() {
    // your load function
}

Drop that in a script tag on your view and the load function will be called once the window is loaded.

The google API probably also provides a way to attach the load event, but I'm not familiar with it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜