Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Include js-files from script? 1

Status
Not open for further replies.

TriKri

Programmer
Jul 31, 2007
7
0
0
SE
Hello!

I have a javaScript inclusion in my html-file, like this:
[tt]<script type="text/javascript" src="interface.js"></script>[/tt]

Is there som way to include more js-files from interface.js? Or do I have to specify every file I include in the html-file?
 
Hi

A couple of week ago we had this question.
Code:
[b]function[/b] includejs(what)
{
  [b]var[/b] js=document.createElement([i]'script'[/i]);
  [b]with[/b] (js) {
    type=[i]'text/javascript'[/i];
    src=what;
  }
  document.getElementsByTagName([i]'head'[/i])[0].appendChild(js);
}

includejs([i]'first.js'[/i]);
includejs([i]'/second.js'[/i]);
includejs([i]'/subdirectory/third.js'[/i]);

Feherke.
 
Aha, smart! Thanks! I never thought of a script as a document element. Now I'm not a pure-javaScript programmer, since I use JavaScript only when I'm creating web applications. But I know it's possible to run a js-file only as it is. And then I suppose you don't have a document element, so [tt]var js=document.createElement('script');[/tt] wouldn't work? How do one do it then?
 
Take care using this method. If you call a function in the file immediately after trying to include it, it may error if the browser hasn't retrieved it from the server yet. An alternative is to use AJAX to preload the script. See faq216-6698 for an example.

Adam
 
Do you need the inclusion to be dynamic, or a static workaround will work? You can include other .js files in interface.js without modifying your html.

Cheers,
Dian
 
Thanks! I think I know how I will do now. :)

 
feherke, what is the [0] for in your script? Isn't it going to work if you just attach it directly in the document head?

 
document.getElementsByTagName returns an array, even if there is only one element with that tag name. Using the index [0] accesses that first element in the array (of which there is only one element).

Lee
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top