Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you dynamically load a javascript file from different domain?

Tags:

javascript

I find this excellent code, posted by aemkei as answers to this questions:

  1. How do you dynamically load a javascript file? (Think C’s #include)
  2. Use javascript to inject script references as needed?

You may write dynamic script tags (using Prototype):

new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});

The problem here is that we do not know when the external script file is fully loaded.

We often want our dependant code on the very next line and like to write something like:

if (iNeedSomeMore){
  Script.load("myBigCodeLibrary.js");  // includes code for myFancyMethod();
  myFancyMethod();                     // cool, no need for callbacks!
}

There is a smart way to inject script dependencies without the need of callbacks. You simply have to pull the script via a synchronous AJAX request and eval the script on global level.

If you use Prototype the Script.load method looks like this:

var Script = {
  _loadedScripts: [],
  include: function(script){
    // include script only once
    if (this._loadedScripts.include(script)){
      return false;
    }
    // request file synchronous
    var code = new Ajax.Request(script, {
      asynchronous: false, method: "GET",
      evalJS: false, evalJSON: false
    }).transport.responseText;
    // eval code on global level
    if (Prototype.Browser.IE) {
      window.execScript(code);
    } else if (Prototype.Browser.WebKit){
      $$("head").first().insert(Object.extend(
        new Element("script", {type: "text/javascript"}), {text: code}
      ));
    } else {
      window.eval(code);
    }
    // remember included script
    this._loadedScripts.push(script);
  }
};

I found that, the code does not work on IE if the all of them is executed in 'file://' protocol, however, it is not the problem since its use case involved real web application.

I tried it once to include http://www.google-analytics.com/urchin.js by google, but from one of web page, but it looks like it cannot request javascript file from different domain.

How we could dynamically add javascript, just like what above scripts does, but from another domain?

like image 424
Nordin Avatar asked Feb 27 '09 03:02

Nordin


People also ask

What is dynamic loading in JavaScript?

Dynamic loading In some situations, we want to load third-party script files dynamically in JavaScript. Those files can be loaded asynchronously in JavaScript. To load a JavaScript file dynamically: Create a script element. Set the src , async , and type attributes.

How do I load a 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 you load third party scripts 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.

What is Dynamic script in JavaScript?

Both AJAX and dynamic JavaScript refer to ways of using JavaScript. Both are methods of creating an action on a web page without loading that entire page in the browser. AJAX and dynamic JavaScript can make a website faster and more responsive to the user. In many ways, AJAX is a subset of dynamic JavaScript.


2 Answers

You can use the onload and onreadystatechange event to understand when the <script> tag is loaded.

var script = new Element("script", {src: "myBigCodeLibrary.js", type: "text/javascript"});

script.onload = script.onreadystatechange = function(){
    if (!this.readyState ||
        this.readyState == "loaded" || this.readyState == "complete") {
        //script is loaded
    }
};
like image 128
Luca Matteis Avatar answered Sep 22 '22 13:09

Luca Matteis


The security model in modern browsers prevents JavaScript from making cross-domain requests. That has holes (see every website exploit since the beginning of the internet), but using them is more than a little shady and it's only a matter of time before they're patched.

like image 41
Rex M Avatar answered Sep 21 '22 13:09

Rex M