While working on a project that uses Google Maps API, I noticed the following problems:
The content below Google maps appeared after a slight delay
Google PageSpeed Insights kept telling me to “eliminate render-blocking JavaScript and CSS in above-the-fold content”
The maps did not load when the page was loaded via AJAX
The maps did not work in jQuery Mobile
All of these problems were caused because I was loading the Google Maps API synchronously. Let me explain. Almost all Google Maps API examples tell you to do this:
<script src=”//maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE”></script>
<script>
function initialize() { /* Map Initialization JavaScript */ }
google.maps.event.addDomListener(window, “load”, initialize);
</script>
This works but it blocks the page to load/render slowly and does not work with AJAX for the following reasons:
The browser stops rendering the page when it encounters the script tag, download the script, execute it, then resume rendering; this explains problem 1 and 2
The downloaded script calls document.write() which makes both asynchronous and AJAX loading impossible; this explains problem