Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Maps library loading blocks the page

I use the following HTML tag to load the Google Maps API :

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

However, it is blocking the loading everything that's below it in the HTML until the script is loaded by the browser.

Is there a way to make this loading non-blocking?

like image 702
Matthieu Napoli Avatar asked Dec 22 '11 19:12

Matthieu Napoli


People also ask

How do I fix Google Maps in WordPress?

Make sure WordPress, your plugins and the theme on your website are up to date. Check which WordPress plugins and themes show the maps from Google Maps. Check their settings to make sure you can now paste your Google Maps API key.


2 Answers

This code gives you a defer function that takes an url and an optional callback. It asynchronously loads your script without blocking page rendering. I've put in a protection so it won't load the same scritp twice, so you can naively call it as many times as you like.

defer = (function () {
    var urls = [];

    return function (url, callback) {
        var inc;

        if (url && urls.indexOf(url) === -1) {
            inc = document.createElement('script');
            inc.async = true;
            inc.src = url;
            inc.onload = callback || function () {};
            document.getElementsByTagName('head')[0].appendChild(inc);
        }
    }
}());

defer('http://maps.google.com/maps/api/js?sensor=false');

This works for any external javascript that doesn't fail on async loading.

like image 124
Munter Avatar answered Oct 03 '22 14:10

Munter


Yes, you can load it asynchronously. Check out this part of the docs: http://code.google.com/apis/maps/documentation/javascript/basics.html#Async

like image 41
Mano Marks Avatar answered Oct 03 '22 15:10

Mano Marks