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?

p.campbell
  • 91,713
  • 61
  • 243
  • 314
Giuseppe Di Federico
  • 2,881
  • 4
  • 18
  • 19

5 Answers5

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
});
Arnaud Leymet
  • 5,262
  • 4
  • 29
  • 46
10

Use the Loading on Demand Loading Strategy

Loading on Demand

The previous pattern loaded additional JavaScript unconditionally after page load, assuming that the code will likely be needed. But can we do better and load only parts of the code and only the parts that are really needed? Imagine you have a sidebar on the page with different tabs. Clicking on a tab makes an XHR request to get content, updates the tab content, and animates the update fading the color. And what if this is the only place on the page you need your XHR and animation libraries, and what if the user never clicks on a tab? Enter the load-on-demand pattern. You can create a require() function or method that takes a filename of a script to be loaded and a callback function to be executed when the additional script is loaded.

The require() function can be used like so:

require("extra.js", function () {
   functionDefinedInExtraJS();
});

Let’s see how you can implement such a function. Requesting the additional script is straightforward. You just follow the dynamic element pattern. Figuring out when the script is loaded is a little trickier due to the browser differences:

function require(file, callback) {
   var script = document.getElementsByTagName('script')[0],
   newjs = document.createElement('script');

  // IE
  newjs.onreadystatechange = function () {
     if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
        newjs.onreadystatechange = null;
        callback();
     }
  };
  // others
  newjs.onload = function () {
     callback();
  }; 
  newjs.src = file;
  script.parentNode.insertBefore(newjs, script);
}

“JavaScript Patterns, by Stoyan Stefanov (O’Reilly). Copyright 2010 Yahoo!, Inc., 9780596806750.”

user278064
  • 9,422
  • 1
  • 30
  • 46
  • this is an absolute life-saver when trying to dynamically load local files from a local (file:///) context... thanks a bunch :) – Zathrus Writer May 10 '13 at 23:07
4

you would just generate the script tag via javascript and add it to the doc.

function AddScriptTag(src) {
    var node = document.getElementsByTagName("head")[0] || document.body;
    if(node){
        var script = document.createElement("script");
        script.type="text/javascript";
        script.src=src
        node.appendChild(script);
    } else {
        document.write("<script src='"+src+"' type='text/javascript'></script>");
    }
}
Evgeny
  • 10,166
  • 8
  • 54
  • 69
rlemon
  • 16,698
  • 11
  • 85
  • 121
0

I think you're loking for this http://unixpapa.com/js/dyna.html

<input type="button" onclick="helper()" value="Helper">

   <script language="JavaScript">
   function helper()
   {
      var head= document.getElementsByTagName('head')[0];
      var script= document.createElement('script');
      script.type= 'text/javascript';
      script.src= 'your_script_url';
      head.appendChild(script);
   }
   </script>
0

I used the Tangim response, but after found that is more easy use jquery html() function. When we make ajax request to html file that have html+javascript we do the follow:

$.ajax({
    url:'file.html',
    success:function(data){
       $("#id_div").html(data); //Here automatically load script if html contain
    }
});
infinito84
  • 1,489
  • 14
  • 8