Loading Google Maps API after the page is displayed
My landing page contains a big google maps portion, which slows down the loading time. I am trying to do the following:
- Load the static elements first so the page loads fast initially.
- Display a loading notification in the map placeholder so that the user knows that the map is coming up
- Load and display the map
I have done this:
$(document).ready(function() {
map_initialize();
}
The map_initialize()
function loads the map into its container div. Howe开发者_如何学编程ver, this still will not display the static elements fist. The page will wait until the map_initialize()
is finished, then load the static elements at the same time as the map.
The window.onload
event will wait for the images, and any other resource on the document, to load before it gets fired:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
Source: Mozilla Dev Center: window.onload
You may also want to check out the following Stack Overflow post for further reading:
- Execute JavaScript When Page Has Fully Loaded
Therefore all you need to do is to set the window.onload
event handler as follows:
window.onload = map_initialize;
I worked on this functionality and faced this issue.Solution is ..
function initMap() {
--google map code--
}
$(document).ready(function () {
google.maps.event.addDomListener(window, 'load', initMap);
});
Without jQuery you could do:
window.addEventListener('load', () => {
map_initialize();
});
If you use the onLoad event the static elements should load before your map. The ready
method in JQuery will run before everything is loaded; it runs as soon as document
is ready.
Try this:
$('body').load(function() {
map_initialize();
});
[edit] I just found this from the user comments in the jQuery documentation : http://api.jquery.com/load-event/#comment-43474051
精彩评论