0

We have a component that contains the following script block to insert a js observable image that gets updated when it comes into view:

<script type="text/javascript">
  document.currentScript.parentNode.insertAdjacentHTML('afterbegin', '<span class="js-dom-observable js-dom-observable--picture"><img src="http://www.fillmurray.com/200/300" data-src="http://www.fillmurray.com/500/500" alt="Image"></span>');
</script>

This works well when the component is loaded directly onto the page, however, when it is in the html as a result of an ajax call and appended to the page, it no longer adds the image - I'm guessing it's because the document.currentScript is no longer the script tag it is in but the script that is executing the ajax:

$.ajax({
  url: `/${APP_NAME}${filterResultEndpoint}`,
  type: 'POST',
  traditional: true,
  data: searchData.getPostData(),
  success: result => {
    $('.results').html(result);
  },
});

Is there a way to make this insertAdjacentHTML in the script tag work in an ajax call - if I replace the insertAdjacentHTML with a simple document.write, it will work in both cases, but I'm unable to use that as it will fail our coding analysis policies

Pete
  • 57,112
  • 28
  • 117
  • 166

1 Answers1

0

document.currentScript is a global variable that changes durning parsing of all the script tags

it becomes null after the DOM have been parsed.

You have to store the element to a variable before making any asynchronous operations

var element = document.currentScript
$.ajax({
  success() {
    element.parentNode.insertAdjacentHTML(...)
  }
})
Endless
  • 34,080
  • 13
  • 108
  • 131
  • hmm, if there are multiple script tags been parsed in the ajax result, how would I handle that? – Pete Nov 11 '20 at 15:25
  • `document.currentScript` can only be one at the time and it will always be the script tag that currently being processed – Endless Nov 11 '20 at 21:27