Vito Gentile
Vito Gentile

Reputation: 14386

Path of a Javascript file inside an iframe with null src

Let's consider this situation.

I have a folder called /jscript, inside which there are two files called my_js_file1.js and my_js_file2.js.

I've also a page, /index.html, like this:

<html>
    <head>
        <script type='text/javascript' src='jscript/my_js_file1.js'></script>
    </head>
    <body>
        <iframe src=''/>
    </body>
</html>

Now, let's assume that, via the my_js_file1.js, I want to add to the <head> tag of the iframe, the following tag:

<script type='text/javascript' src='my_js_file2.js'></script>

Is the above src correct? If yes, it means that the document inside the iframe refers to the "working directory" of the javascript file.

If the previous is not, does the following solution work?

<script type='text/javascript' src='jscript/my_js_file2.js'></script>

(Working of this last one means that the "working directory" is the same of the html file)

Regardless of the result, is there someone is able to explain the correct behaviour?

Upvotes: 1

Views: 987

Answers (1)

ComFreek
ComFreek

Reputation: 29434

jscript/my_js_file2.js should be correct.

Documents and elements do have a so-called "base URI". It is used for resolving relative links such as yours.

The base URL of a document defaults to the document's address (as displayed by the browser and available in window.location), but can change from the default:

• When an HTML <base> tag is found in the document;
• When this is a new document created dynamically.

Node.baseURI - Mozilla Developer Network (MDN)

Under the assumption that your HTML file does not contain any <base> tags, the base URI is /index.html.

You can prove this behavior by verifying the value of document.baseURI:

<!doctype html>
<html>
    <head>
        <script src="subdir/include.js"></script>
    </head>
    <body>
    </body>
</html>

include.js:

alert(document.baseURI);

Upvotes: 1

Related Questions