7

is there anyway to load other JS files from within a single JS file. I would like to point my individual pages "ITS" js file and that js file would load jquery, other js files.

I know i can just pop all these into the html i.e.

I was thinking of separations of concerns so i was wondering if anything exists already without me reinventing the wheel....

That i would just need to edit home.js to change what other js (jquery etc) are loaded for home.htm ... home.htm would just point to home.js

Thanks

asked Oct 24, 2009 at 15:58

5 Answers 5

15

You can take a look at dynamic script loading. Here's an excerpt from the article:

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'helper.js';
head.appendChild(script);
answered Oct 24, 2009 at 16:07
Sign up to request clarification or add additional context in comments.

Comments

3

For external domain JS link

var loadJs = function(jsPath) { 
 var s = document.createElement('script');
 s.setAttribute('type', 'text/javascript');
 s.setAttribute('src', jsPath);
 document.getElementsByTagName('head')[0].appendChild(s);
};
loadJs('http://other.com/other.js'); 

For same domain JS link (Using jQuery)

var getScript = function(jsPath, callback) {
 $.ajax({
 dataType:'script',
 async:false,
 cache:true,
 url:jsPath,
 success:function(response) {
 if (callback && typeof callback == 'function') callback();
 }
 });
};
getScript('js/other.js', function() { functionFromOther(); }); 
answered Apr 16, 2010 at 1:12

Comments

2

This is similar to Darin's solution, except it doesn't make any variables.

document.getElementsByTagName('head')[0].appendChild(document.createElement("script")).src = "helper.js";
answered Oct 24, 2009 at 22:17

1 Comment

Or you could just wrap the more readable solution in (function() {...})();
1

Google offers centrally hosted versions of the major javascript libraries like jQuery. They can be dynamically loaded using the google loader.

http://code.google.com/apis/ajaxlibs/documentation/

answered Oct 24, 2009 at 16:09

Comments

1

I'd suggest you take a look at labJS. It's a library made specifically to load Javascript. As they say..."The core purpose of LABjs is to be an all-purpose, on-demand JavaScript loader, capable of loading any JavaScript resource, from any location, into any page, at any time."

See the labJS home page for more information.

answered Dec 2, 2009 at 22:00

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.