How to load js file using javascript

I want to solve a nasty problem that appears yesterday during a demo to a client. We are using jquery by loading it from google api. But yesterday our ISP started causing some problems and was not loading jq.js properly.

So, I really want to download a local file from the server if the google api has an extrange behavior (not that it happens often, but at least doing local demos won't hurt us anymore).

I know what <script type="txt/javascript" src="googleapi"> somejs </script>

is doing somejs when the file in src doesn't load, but doesn't know how the file can be loaded.

Thanks in advance

0


a source to share


4 answers


inside you can put the following lines:



var localScript = document.createElement("script");
localScript.type = "text/javascript";
localScript.src = "localJQ.js";
document.body.appendChild(localScript);

      

+1


a source


Edit: I was a little nervous. The solution given by peirix is ​​correct. I just use his code to prevent the wrong solution from polluting this area. You can do

var localScript = document.createElement("script");
localScript.type = "text/javascript";
localScript.src = "localJQ.js";
document.body.appendChild(localScript);

      

to load javascript dynamically.



However, it depends on race conditions, however, if your page has scripts that depend on this script. Use with care.

This presentation - Even Faster Websites - details on how to load external files via javascript.

0


a source


Teaching grandma to suck eggs is possible, but why not just use a local copy on the demo machine?

0


a source


This doesn't directly answer your question, but jQuery creator John Resig has an interesting post about executing a script tag when there is also a src attribute.

0


a source







All Articles