6

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

3
  • the datatype you are receiving in this context is text but you are asking for Script,,, so you need to return script,, so the datatype is script Commented Feb 25, 2012 at 4:18
  • @SamArulRaj, geScript already parses the return as script, there is no need to tell getScript to parse as script. Plus he is requesting a .js file so I don't get what you are saying. Commented Feb 25, 2012 at 4:22
  • @Semur, are you using the correct path in getScript function? And also make sure you have loaded the jquery file. Check you browser console(chrome or firefox) to see if it throws an error. Commented Feb 25, 2012 at 4:33

3 Answers 3

11

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

Comments

10

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

$.ajax({
  type: "GET",
  url: "test.js",
  dataType: "script"
});

1 Comment

This is simply copying out exactly what the jQuery manual says is shorthand for getScript. If his current method doesn't work, this probably won't either. I suspect the problem is elsewhere.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.