Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load external js file with jQuery

Looked for it everywhere, and found the answer but lost. anyone knows how to load an external .js file from another js file?

main_lobj1.onreadystatechange = function(){     
  if (main_lobj1.readyState == 4) {if (main_lobj1.status == 200) { 
    document.getElementById("middleDiv_m").innerHTML=main_lobj1.responseText;  
  jQuery.getScript('jquery/tabs.js')        
  }
}

innerHTML works and responce text is pasted. The problem is that JS is not working in that document. jQuery.getScript should be loading that external js file, but it doesnt

like image 267
Semur Nabiev Avatar asked Feb 25 '12 04:02

Semur Nabiev


People also ask

How do I import an external file into JavaScript?

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 run a JavaScript file from URL?

To execute JavaScript in a browser you have two options — either put it inside a script element anywhere inside an HTML document, or put it inside an external JavaScript file (with a . js extension) and then reference that file inside the HTML document using an empty script element with a src attribute.


3 Answers

Exactly for this reason a function $.getScript() exist in jquery. You can use it simply in this way:

$.getScript("test.js", function( data, textStatus, jqxhr ) {
  // this is your callback.
});
like image 104
Salvador Dali Avatar answered Oct 17 '22 22:10

Salvador Dali


This is the way you can do it to load an external js file to Jquery

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});
like image 45
Sam Arul Raj T Avatar answered Oct 18 '22 00:10

Sam Arul Raj T


If you call an external script you want to base your script on you may want to take note that ajax-based jquery script are asynchronous by defealt.

Calling an external script asynchronousily will cause the rest of the rest being executed before the external script is loaded.

Today I ran into the same problem which was easily being solved by making a small adition to Sam Arul Raj's post:

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script",
  async: false
});
like image 2
Kevin Driessen Avatar answered Oct 17 '22 23:10

Kevin Driessen