Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get on Javascript resource to load another one?

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.

like image 447
Stephen C Avatar asked Oct 04 '10 09:10

Stephen C


2 Answers

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.

like image 113
Vikas Avatar answered Sep 30 '22 02:09

Vikas


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

like image 31
Brad Mace Avatar answered Sep 30 '22 02:09

Brad Mace