1

Possible Duplicate:
How may I reference the script tag that loaded the currently-executing script?

Is there any way to get a reference to the currently running script element if it was appended dynamically after page load? The answers to this question do not work as I do not know the tag ID and the [scripts.length-1] method fails when multiple tags have been appended in succession.

Community
  • 1
  • 1
James
  • 389
  • 2
  • 17

1 Answers1

3

Since the executing script presumably "knows" the name it was loaded with the following should work:

for (var s, scripts = document.getElementsbyTagName ('script'), i = scripts.length; i--;)
  if ((s = scripts[i]).src.indexOf ('scriptname.js') < 0 && s.id && !test (s.id)) {
     alert ("Script " + s.src + " id " + s.id + " not yet processed");
  }
HBP
  • 15,685
  • 6
  • 28
  • 34
  • Yes, if you know the name of the script, this works. In my specific case, one script may be loaded multiple times and the ID of the script tag is the only distinction. The script contains the implementation of a search control which may be used multiple times on a page. Appending the script tag with this script src implements the control. – James Mar 10 '11 at 15:37
  • You say you do not know the tag id, but surely you know the filename – HBP Mar 10 '11 at 15:40
  • So once a script is executed, you can determine the fact by examining the DOM, search the scripts as per my code above until you find one whose id has not yet been processed. I'll do an example edit – HBP Mar 10 '11 at 15:47
  • That's not a direct method of accessing the element but it should work for my purposes. If I mark each element completed as it's finished I can search for unmarked elements to know in which element I'm running. Thanks for the solution. – James Mar 10 '11 at 17:30