Skip to main content

Javascript document.write alternative

Reading time: 1 minute Suggest an edit

When a script is loaded synchronously, its element's position in the DOM can be determined. With this information, the <script> element can act as a pivot point for inserting dynamic content. This eliminates the need for document.write, a function which wreaks havoc where AJAX is involved (and flies in the face of modern web development best practices).

<!doctype html>
<meta charset="utf-8"/>
<title>document.write alternative</title>
<p>Here is some content.</p>
<!– load a script; any script –>
<script type="text/javascript" src="//"></script>
<!– here is our document.write analog; could just as easily be a remote file –>
<script type="text/javascript">
// get the "last" script on the page
var s = document.getElementsByTagName('script');
s = s[s.length - 1];
var p = document.createElement('p');
p.innerHTML = "Here is some dynamic content.";
s.parentNode.insertBefore(p, s);
<!– load another script; any other script –>
<script type="text/javascript" src="//"></script>
<p>Here is some more content.</p>

[View the demo on](