Alex Rivera | Logout

Load JavaScript dynamically

Asked 2011-09-03T13:20:40.620
15

I have a web page and a canvas with Google Maps embedded in it. I am using jQuery on this site.

I want to load Google Maps API only if the user clicks on "Show me the map". Further, I want to take away the whole loading of the Google Maps from the header in order to improve my page performance.

So I need to load JavaScript dynamically. What JavaScript function I can use?

Edit
Report

1 Answer

27

You may want to use jQuery.getScript which will help you load the Google Maps API javascript file when needed.

Example:

$.getScript('http://maps.googleapis.com/maps/api/js?libraries=geometry&sensor=true', function(data, textStatus){
   console.log(textStatus, data);
   // do whatever you want
});
answered 2011-09-03T13:23:19.810

Your Answer