26. 10. 2018

Javascript document.write replacement

Replacement of document.write can be combination of insertAdjacentHTML() method and document.currentScript property.

The insertAdjacentHTML() method of the Element interface parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position:

The Document.currentScript property returns the <script> element whose script is currently being processed. Best position to add new HTML will be beforebegin - new HTML will be inserted before <script> itself.

<script>
  document.currentScript.insertAdjacentHTML(
    'beforebegin', 
    'this is the document.write alternative'
  );
</script>