Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load google maps apis scripts when needed? jquery.getScript()?

I am using a google map with the full maps api on my website. The map is only visible and used once a specific link (e.g. Show Map) is clicked. Since this maps api is a rather large js file I want to load the api only when it's needed and not on page load like i'm doing it right now.

Right now I have this in my <head>:

<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=true&amp;key=ABQIAAAAnf9W..." type="text/javascript"></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>

I am using jQuery and I have a seperate script.js file where I store all my javascript.

The map I only shown when I click the following item:

$('#googleMap').live('click', function(e) {

Is it possible to use jquery getScript() to load the above scripts only when this link is clicked? Or at least load it "onLoad()" and not "onDomReady"?

like image 252
matt Avatar asked Dec 27 '22 22:12

matt


1 Answers

First of all, you don't need to include both of those scripts. You only need:

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

Secondly, you can use the google loader (see the "Dynamic Loading" section) to fire up maps when the user requests it, like this:

$("#foo").click(function() {
    google.load("maps", "3", {other_params:'sensor=false', callback: function(){
        alert('maps API loaded!');
        var map; 
        // do stuff with your map
    });
});
like image 158
karim79 Avatar answered Mar 07 '23 01:03

karim79