I have a JavaScript that inserts HTML into the DOM at the spot where the JavaScript code is placed. The script finds the location where the code is installed by cycling through all script elements via document.getElementsByTagName('script') and then uses insertBefore to display the HTML in that spot.
This works great when only one of these scripts is installed on a given page. However, when more than one is installed I occasionally get multiple copies of the same content even though the scripts return different HTML. I also get missing content sometimes.
I need a bullet-proof way of adding multiple blocks of HTML to a page at the spot where a given scripts are installed.
Pseudocode:
Host Document installation:
script SRC='InsertHTML.aspx?UniqueID=1'
script SRC='InsertHTML.aspx?UniqueID=2'
InsertHTML.aspx JavaScript:
- createElement myDiv and add HTML via myDiv.innerHTML
- Get all Script tags on page via document.getElementsByTagName('script')
- Find script tag (sTag) that contains = 'UniqueID=1' etc
- Use sTag.parentNode.insertBefore(myDiv,sTag)
Live example: https://www.thefinancials.com/dev/GREYSTON_3WidgetDemo.html
Again, this works flawlessly when only one InsertHTML.aspx appears on the page and usually works with multiple instances. But sometimes duplicate output appears and other times output from some instances of the script do not appear at all.
What's the best way to accurately target the desired location of output from my aspx script?