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:
document.write: not elegant, but seems to do the job.
[Edit] Based on the reply from idealmachine, I am thinking about one more option:
[Edit] Another idea, also inspired by the replies so far:
Out of the box : document.currentScript (not supported by IE)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With