Get script-tag that called certain function

Let's say I have first script, that contains function export

function export(*params*){
  let callerScriptReference = ....;
  .....
}

then I have a second script, where I call this function

export(*params*);

Is it possible to get reference to that second script from within export function body? I'd like to get some "data-*" attribute from that script tag.

Scripts are added to the page in random order.

Hopefully you understand what I'm trying to accomplish :D

Thanks for any suggestions or help.

Upvotes: 0

Views: 350

Answers (2)

Barmar
Barmar

Reputation: 780949

As far as I can tell, there's no built-in way to get information about the <script> tag that contains the calling code, so you'll need to pass it explicitly.

function export(callerscript, otherparams...) {
    ...
}

The caller would do:

export(document.currentScript, otherargs...);

If you're doing it in a function, you can capture the value in a closure variable using an IIFE.

var someFun = (function(curScript) {
                return function(stuff) {
                    export(curScript, stuff);
                }; })(document.currentScript);
someFun(stuffArgs);

Upvotes: 1

Matt Bajorek
Matt Bajorek

Reputation: 309

If you are in the browser you can just add another script tag in the html body. This will allow the function to share the same scope.

If you are in nodejs, if you are using ES5 (most supported currently):

  • script1.js has at the end:

module.exports = function funName() { }

  • script2.js has at the beginning:

var funName = require('script1');

Upvotes: 0

Related Questions