If you can, avoid using document.write
. Here is a common way to insert a script, so that it gets executed:
document.addEventListener('DOMContentLoaded', function(){
var s = document.createElement('script');
s.src = "my_script.js";
document.body.appendChild(s);
}, false);
If you have any other HTML you'd like to add, you could use innerHTML
, but it's sometimes better to avoid using it, since it will replace all the elements (and maybe break some event listeners that were set before). Instead, you can use insertAdjacentHTML
. Note that if a script is added via this method, it will not be executed:
document.addEventListener('DOMContentLoaded', function(){
var code = '<style>.class{color:red}</style><div class="class">Hello</div>';
document.body.insertAdjacentHTML('afterbegin', code);
}, false);
You can choose where the code gets appended by using these options: beforebegin
, afterbegin
, beforeend
or afterend
.