How to dynamically load the Google Maps javascript API (On demand loading)

Normally google maps js api is loaded at the time of page load via a script tag with src set. If map is not so major feature of your application or you want to reduce page download time, you can defer loading the javascript load it when required.
This is a javascript pattern called On demand javascript.

Bottomline is: “JavaScript being pulled from the server after the page has loaded“.

Google maps provide the facility to dynamically load the api when required.  So no need to load it at the time of page load. I will present an example here which will load the maps api on click of a button. Here is how to do it.

View Demo

As said above, DO NOT load any javascript api from Google using script tags. Instead we will use a button.

To load the api onclick of this button, create a script tag, set its src and append it to document. This will load the Google AJAX API required to load other google APIs.

Do not forget to replace the API key above with your API key. (You can get an API key by signing up here)

Important: Note the callback=loadMaps in script.src. This is the thing doing all the magic. It tells which function to call when AJAX API has loaded. In above case it will call loadMaps function. So, let us define that.

loadMaps function uses load method of google AJAX API to load a specific api. Above we loaded “maps” version “2”. Again callback is the name of function that will be called when maps api is loaded. callback function will be called only when the maps api is loaded successfully.

That is all to it. I have created a demo along these lines. View source for code. You can see it here.

Related Posts

20 thoughts on “How to dynamically load the Google Maps javascript API (On demand loading)”

  1. Thanks you very much. I was stumbling about this issue for how many hours already. This solution is pretty nice.

  2. Thanks so much, very useful!!!!

    How can I unload the map (along with API to free up resources) via button click?

  3. I am sure this post has touched all the internet
    viewers, its really really nice article on building up new website.

  4. i want to match a default location to other one by one ,to get distance and duration via google map api,its working but after end of the loop it cant break and display nothing, i have to see the results by alert() help me out here is my code…

Leave a Reply