11

I do lazy loading of the google maps api v3 javascript

The documentation says about putting as a callback parameter in the url the name of the function, which will be executed, when the script has loaded.

 $(document).ready(function(){
   var s = document.createElement("script");
   s.type = "text/javascript";
   s.src  = "http://maps.google.com/maps/api/js?v=3&sensor=true&callback=gmap_draw";
   $("head").append(s);
 });

So I must define the gmap_draw() function.

When I enclose this function in the domready block, it is not visible.

Any workarounds of this issue ? (except putting the function out of the domready block)

astropanic
  • 10,800
  • 19
  • 72
  • 132

2 Answers2

32

Another option is to use Google Loader:

$.getScript('https://www.google.com/jsapi', function()
{
    google.load('maps', '3', { other_params: 'sensor=false', callback: function()
    {
        // Callback code here
    }});
});
Jonathan
  • 18,229
  • 10
  • 57
  • 56
22

Because the callback must be global, you could make one by accessing window from within the ready handler.

$(document).ready(function(){
   var s = document.createElement("script");
   s.type = "text/javascript";
   s.src  = "http://maps.google.com/maps/api/js?v=3&sensor=true&callback=gmap_draw";
   window.gmap_draw = function(){
       alert ("Callback code here");
   };
   $("head").append(s);  
});
Chris Laplante
  • 29,338
  • 17
  • 103
  • 134
  • Is there no way to enter a namespaced callback name ? As you said, the above function is global, so it's more readable to put it out of the jquery block. Nice approach, thanks for sharing – astropanic Nov 05 '10 at 00:42
  • If by namespaced callback do you mean defining a callback in a "myNamespace" (or similar) object? – Chris Laplante Nov 05 '10 at 00:44
  • let's suppose we have an gmapsFactory object, and I want to execute a gmapsFactory.init() – astropanic Nov 05 '10 at 00:46
  • As long as `gmapsFactory` is defined in the global namespace, then that will work. The callback you would put in the URL in this case would be `gmapsFactory.init` – Chris Laplante Nov 05 '10 at 00:49