Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load JavaScript dynamically [duplicate]

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?

like image 354
Giuseppe Di Federico Avatar asked Sep 03 '11 13:09

Giuseppe Di Federico


People also ask

How do I load a JavaScript script?

For loading a script file dynamically using JavaScript, the basic steps are: Create the script element. Set the src attribute on the script element to point to the file we want to load. Add the script element to the DOM.

How do I include an external js file in another JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

How do I load an external script dynamically in react?

We start by creating an empty <script></script> tag in the memory as script and then assign the necessary attributes to its src and the id to identify the script later. Finally, we append the script to our <body></body> tag to actually load this.


2 Answers

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
});
like image 62
Arnaud Leymet Avatar answered Oct 07 '22 00:10

Arnaud Leymet


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.”

like image 35
user278064 Avatar answered Oct 06 '22 23:10

user278064