I'm trying to do something like a C #include "filename.c"
, or PHP include(dirname(__FILE__)."filename.php")
but in javascript. I know I can do this if I can get the URL a js file was loaded from (e.g. the URL given in the src attribute of the tag). Is there any way for the javascript to know that?
Alternatively, is there any good way to load javascript dynamically from the same domain (without knowing the domain specifically)? For example, lets say we have two identical servers (QA and production) but they clearly have different URL domains. Is there a way to do something like include("myLib.js");
where myLib.js will load from the domain of the file loading it?
Sorry if thats worded a little confusingly.
I've coded a simple function which allows to get the absolute location of the current javascript file, by using a try/catch method.
You can see it here.
Regardless of whether its a script, a html file (for a frame, for example), css file, image, whatever, if you dont specify a server/domain the path of the html doc will be the default, so you could do, for example,
<script type=text/javascript src='/dir/jsfile.js'></script>
or
<script type=text/javascript src='../../scripts/jsfile.js'></script>
If you don't provide the server/domain, the path will be relative to either the path of the page or script of the main document's path
The accepted answer here does not work if you have inline scripts in your document. To avoid this you can use the following to only target
<script>
tags with a[src]
attribute.This effectively captures the last external .js file, solving some issues I encountered with inline JS templates.