0

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:

  1. createElement myDiv and add HTML via myDiv.innerHTML
  2. Get all Script tags on page via document.getElementsByTagName('script')
  3. Find script tag (sTag) that contains = 'UniqueID=1' etc
  4. 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?

  • This is where `document.write()` is useful. It writes to the document right after the script. – Barmar Oct 17 '22 at 16:20
  • That's what I'm trying to avoid because documnet.write is considered an insecure way to add content to a page. Adding via the DOM is the accepted way to add content. – Kurt Walter Oct 17 '22 at 20:43
  • Then you should define a function in the JS file, and call the function with the DOM element to append the new DIV to, rather than depending on the position of the script tag. – Barmar Oct 17 '22 at 20:46
  • See https://stackoverflow.com/questions/403967/how-may-i-reference-the-script-tag-that-loaded-the-currently-executing-script for how to reference the current script tag. You can use that to append to the DOM after it. – Barmar Oct 17 '22 at 20:47

0 Answers0