Find own origin in JavaScript

javascript, jquery

Solution

When a script is called, unless it is marked as `defer` or `async`, it will always be the last element on the page at that moment in time (since it's blocking).

Using this, you can do the following:

var scripts = document.getElementsByTagName('script'),
    mylocation = scripts[scripts.length-1].getAttribute("src");

Then do with that whatever you want.

Problem

Is there a way to find the origin of the current running script? I would like to add a different behavior depending where the script was loaded from. e.g. was loaded from: ``` http://localhost:8080/js/myscript.js ``` vs ``` http://www.myhost.com/js/myscript.js ``` I'm not the one who loads is so I can't add some info in load time, and the script is loaded dynamically using `$.getScript()`, so I can't look for the element.

Original source

Related problems