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?

3
  • You may want to check this question: stackoverflow.com/questions/310583/… Commented Sep 3, 2011 at 13:24
  • 3
    @Igor Since he's using jQuery already, using $.getScript should remove the hassle. Commented Sep 3, 2011 at 13:26
  • @Arnaud Yes, you're probably right. Commented Sep 3, 2011 at 13:27

5 Answers 5

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
});
Sign up to request clarification or add additional context in comments.

1 Comment

Beware that the success callback is called once the script has been loaded, before it has been executed.
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.”

1 Comment

this is an absolute life-saver when trying to dynamically load local files from a local (file:///) context... thanks a bunch :)
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>");
    }
}

2 Comments

Are you sure that document.getElementsByTagName is cross-browser enough?
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>

Comments

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
    }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.