Include an external JS file from another js file or server-side processTag(s): Language

To include some JavaScript from an HTML file is simple:
<script type="text/javascript" src="external.js"></script>

This HowTo is useful if you need to include another JS file from "external.js" or to do a "conditionnal include". The included script is inserted into the DOM and not using document.write.

Let's say we have a JS file called second.js.

function second() { alert("second"); }

first.js is designed to include the second.js.

var imported = document.createElement("script");
imported.src = "second.js";

function first() { alert("first"); }
The HTML contains markup to load first.js (and second.js as a side effect).
<SCRIPT SRC="first.js"></SCRIPT>
<a href="javascript:first()">method in first js</a><br/>
<a href="javascript:second()">method in second js ("included" by the first)</a>
Using this idea, it is easy to include some javascript generated by a server-side process (eg. JSON object).
var e = document.createElement("script");
e.src = '';

See also this HowTo : Include a file into a page (Ajax style).

See also this HowTo : Insert a text file into a page.

blog comments powered by Disqus