Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended method to locate the current script?

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.
like image 848
Christophe Avatar asked Nov 13 '10 11:11

Christophe


2 Answers

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

like image 67
Stranded Kid Avatar answered Sep 21 '22 03:09

Stranded Kid


I've worked for OnlyWire which provides, as their main service, a widget to put on your site.

We use the var scripts = document.getElementsByTagName("script"); var thisScript = scripts[scripts.length - 1]; trick and it seems to work pretty well. Then we use thisScript.parentNode.insertBefore(ga, thisScript); to insert whatever we want before it, in the DOM tree.

I'm not sure I understand why you consider this a "heavy" solution... it doesn't involve iteration, it's a pure cross-browser solution which integrates perfectly.

like image 45
Luca Matteis Avatar answered Sep 19 '22 03:09

Luca Matteis