Recommended method to locate the current script?

Christophe picture Christophe · Nov 13, 2010 · Viewed 8.7k times · Source

I am writing a script that needs to add DOM elements to the page, at the place where the script is located (widget-like approach). What is the best way to do this?

Here are the techniques I am considering:

  1. Include an element with an id="Locator" right above the script. Issues:
    • I don't like the extra markup
    • If I reuse the widget in the page, several elements will have the same "Locator" id. I was thinking about adding a line in the script to remove the id once used, but still...
  2. Add an id to the script. Issues:
    • even though it seems to work, the id attribute is not valid for the script element
    • same issue as above, several elements will have the same id if I reuse the script in the page.
  3. Use getElementsByTagName("script") and pick the last element. This has worked for me so far, it just seems a little heavy and I am not sure if it is reliable (thinking about deferred scripts)
  4. document.write: not elegant, but seems to do the job.

  5. [Edit] Based on the reply from idealmachine, I am thinking about one more option:

    • Include in the script tag an attribute, for example goal="tabify".
    • Use getElementsByTagName("script") to get all the scripts.
    • Loop through the scripts and check the goal="tabify" attribute to find my script.
    • Remove the goal attribute in case there's another widget in the page.
  6. [Edit] Another idea, also inspired by the replies so far:

    • Use getElementsByTagName("script") to get all the scripts.
    • Loop through the scripts and check innerHTML to find my script.
    • At the end of the script, remove the script tag in case there's another widget in the page.

Answer

Stranded Kid picture Stranded Kid · Sep 23, 2015

Out of the box : document.currentScript (not supported by IE)