0

I'm not sure the title of question is all right, as well as how much my question is valid.

Here is scenario:

// HTML

<script src="/script.js" data-app="app.js" />

// script.js

$(function () {

  var script = // ???

});

Inside the js code, I want to get reference to original tag, the one who initialized the loading on "/script.js", so I'm able to check the data-app attribute.

Is that possible?

Alexander Beletsky
  • 19,453
  • 9
  • 63
  • 86
  • possible duplicate of [How may I reference the script tag that loaded the currently-executing script?](http://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script) – ThiefMaster May 23 '12 at 07:18
  • there is a document.scripts property on chrome and IE (for long time), i don't know if its standard (i dont think so) and what browsers support it, but if its for debuggiong purposes and you can control the browser version then its ok to use it instead of bellow proposed $("...") jquery stuff – neu-rah May 23 '12 at 07:29

4 Answers4

3

You can enumerate the scripts in document.scripts and recognize yours with its src property.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
3
$('script').last().data('app');

Note that this may not be in a DOM ready block. The only place where you can access the current script tag is when it executes for the first time. An async callback such as the DOM ready event would not qualify for this. You can simply store the value in a variable though and then use it from inside your event:

(function() {
    var app = $('script').last().data('app');
    $(document).ready(function() {
        // do stuff
    });
})();
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
1

I don't think that there is a "proper" way to get your tag. However, in theory, when your script runs the corresponding tag should be the last one inserted into the document. So putting code like this into script.js works:

var child = document;
while (child && child.localName != "script")
  child = child.lastChild;

if (child)
  alert("My script tag: " + child);

You will need to run this code when the script loads and remember the script tag if you need it after the initial load.

Wladimir Palant
  • 56,865
  • 12
  • 98
  • 126
1
document.scripts[document.scripts.length-1].src

i don't know what browser support it (IE and chrome, yes)

neu-rah
  • 1,662
  • 19
  • 32
  • I think that all browsers support `document.scripts` - but it is a backwards compatibility property, in modern browsers it is exactly the same things as `document.getElementsByTagName("script")`. – Wladimir Palant May 23 '12 at 07:33
  • well the last will traverse the DOM.. but with same result i think – neu-rah May 23 '12 at 07:34