0

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.

Matúš Čongrády
  • 1,340
  • 3
  • 17
  • 29
  • just find the script tag, you don't need the script contents. – dandavis Jul 05 '16 at 20:06
  • Can you put it in an argument to the `export()` function? See http://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script for how the caller can get a reference to their own script tag. – Barmar Jul 05 '16 at 20:08
  • Yes, I can pass it as a parameter. But I'm creating a little framework that loads resources dynamically in the browser. No bundling, no concatenation. (optimized for http/2). And everything that shortens the syntax is much appretiated. In fact, I want to specify module-name in "data-module" attribute. This attribute then tells me, from within which module the export function was called. – Matúš Čongrády Jul 05 '16 at 20:13

2 Answers2

1

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);
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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');

Matt Bajorek
  • 189
  • 2
  • 5