1

I have an external JavaScript file and I'd like to know the src attribute value URL that was used to include it in the tag from the HTML document. For example:

<script src='https://foo.bar/baz.js'><script>

And then inside baz.js I'd like to write this code:

let mysrc = getMySrc() // Should return https://foo.bar/baz.js

Is it possible to write a getMySrc() function that does this?

1

2 Answers 2

1

Use:

const src = document.currentScript.getAttribute('src');

This works because document.currentScript will refer to the script tag corresponding to the currently running script.

Sign up to request clarification or add additional context in comments.

Comments

0

In addition to the answer by @CertainPerformance. To get the resolved URL and not just what the script parameter stated:

const url = document.currentScript.src;

To get the directory where it originated:

let url = new URL(document.currentScript.src);
const dir = url.origin + url.pathname.replace(/\/[^\/]+$/, '/');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.