views:

38

answers:

2

I have a scenario where I want a web page to contain a <link> to one Javascript resource, and have that resource load two other Javascript resources from the same webserver. Is this possible? Can it be done in a browser-independent fashion?

This may sound a bit unusual, but there are complicated reasons why I'd like to be able to do this, and why combining the resources into a single file is ... awkward.

+2  A: 

If I'm not wrong Javascript resource is nothing but your *.js files, Right? So You can include any number of js in your page, with <script> tag. e.g.

<script type="text/javascript" src="MyDomain/js/abc.js"></script>
<script type="text/javascript" src="MyDomain/js/xyz.js"></script>

Also, in one js file, you can import another js file, by calling following function:

function IncludeJavaScript(jsFile)
{
  document.write('<script type="text/javascript" src="'
    + jsFile + '"></scr' + 'ipt>'); 
}

EDIT:

Or another way to write same function:

function includeJS( jsPath )
{
    var js = document.createElement("script");
    js.setAttribute("type", "text/javascript");
    js.setAttribute("src", jsPath);
    document.getElementsByTagName("head")[0].appendChild(js);
};

Call these functions inside you js file.

Vikas
Thanks. That worked a charm.
Stephen C
Later I thought, you are looking `@import` in JavaScript! Like we use in CSS.. For css: `@import url("/ami/css/style.css");`
Vikas
+1  A: 

It appears what you're looking for is typically referred to as On-Demand javascript

bemace