Including a .js file within a .js file

Javascript

Javascript Problem Overview


I'd like to know if it is possible to include a .js file within another .js file?

The reason for me wanting to do this is to keep client includes to a minimum. I have several .js files already written with functions that are needed by the client. The client would have an html file which he/she manages with a .js file include (my .js file).

I could re-write a new .js file with all the functions in it or, to avoid doing double work, figure out a way to write a .js file that includes other .js files.

Javascript Solutions


Solution 1 - Javascript

I basically do like this, create new element and attach that to <head>

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

You may also use onload event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.

x.onload=callback_function;

Solution 2 - Javascript

The best solution for your browser load time would be to use a server side script to join them all together into one big .js file. Make sure to gzip/minify the final version. Single request - nice and compact.

Alternatively, you can use DOM to create a <script> tag and set the src property on it then append it to the <head>. If you need to wait for that functionality to load, you can make the rest of your javascript file be called from the load event on that script tag.

This function is based on the functionality of jQuery $.getScript()

function loadScript(src, f) {
  var head = document.getElementsByTagName("head")[0];
  var script = document.createElement("script");
  script.src = src;
  var done = false;
  script.onload = script.onreadystatechange = function() { 
    // attach to both events for cross browser finish detection:
    if ( !done && (!this.readyState ||
      this.readyState == "loaded" || this.readyState == "complete") ) {
      done = true;
      if (typeof f == 'function') f();
      // cleans up a little memory:
      script.onload = script.onreadystatechange = null;
      head.removeChild(script);
    }
  };
  head.appendChild(script);
}

// example:
loadScript('/some-other-script.js', function() { 
   alert('finished loading');
   finishSetup();
 });

Solution 3 - Javascript

There is no straight forward way of doing this.

What you can do is load the script on demand. (again uses something similar to what Ignacio mentioned,but much cleaner).

Check this link out for multiple ways of doing this: http://ajaxpatterns.org/On-Demand_Javascript

My favorite is(not applicable always):

<script src="dojo.js" type="text/javascript">
dojo.require("dojo.aDojoPackage");

Google's closure also provides similar functionality.

Solution 4 - Javascript

A popular method to tackle the problem of reducing JavaScript references from HTML files is by using a concatenation tool like Sprockets, which preprocesses and concatenates JavaScript source files together.

Apart from reducing the number of references from the HTML files, this will also reduce the number of hits to the server.

You may then want to run the resulting concatenation through a minification tool like jsmin to have it minified.

Solution 5 - Javascript

I use @gnarf's method, though I fall back on document.writelning a <script> tag for IE<7 as I couldn't get DOM creation to work reliably in IE6 (and TBH didn't care enough to put much effort into it). The core of my code is:

if (horus.script.broken) {
	document.writeln('<script type="text/javascript" src="'+script+'"></script>');	 
	horus.script.loaded(script);
} else {
	var s=document.createElement('script');
	s.type='text/javascript';
	s.src=script;
	s.async=true;

	if (horus.brokenDOM){
		s.onreadystatechange=
			function () {
			    if (this.readyState=='loaded' || this.readyState=='complete'){
				    horus.script.loaded(script);
			    }
		}
	}else{
		s.onload=function () { horus.script.loaded(script) };
	}

	document.head.appendChild(s);
}

where horus.script.loaded() notes that the javascript file is loaded, and calls any pending uncalled routines (saved by autoloader code).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionYo MommaView Question on Stackoverflow
Solution 1 - JavascriptYOUView Answer on Stackoverflow
Solution 2 - JavascriptgnarfView Answer on Stackoverflow
Solution 3 - JavascriptrAmView Answer on Stackoverflow
Solution 4 - JavascriptDaniel VassalloView Answer on Stackoverflow
Solution 5 - JavascriptPete JordanView Answer on Stackoverflow