document.write vs appendChild

六月ゝ 毕业季﹏ 提交于 2019-12-02 23:06:12

I came across this while researching for the same. After some testing, I conclude that, yes, there is a major difference between those two methods. On modern browsers, this is not so much on the loading or execution time but the sequence in which the scripts are being evaluated. For example, if you have the following:

someScript.js

console.log('2');

index1.htm

<script>
console.log('1');
 var script = document.createElement('script');
 script.src = 'someScript.js';
 document.write(script.outerHTML);
</script>
<script>
console.log('3');
</script>

index2.htm

<script>
console.log('1');
 var script = document.createElement('script');
 script.src = 'someScript.js';
 document.body.appendChild(script);
</script>
<script>
console.log('3');
</script>

Running index1.htm on your console will give you the sequence "1, 2, 3". Running index2.html will give you the sequence "1, 3, 2" instead. If there are external scripts being requested, these will load ahead of the dynamically requested someScript for both methods.

Important thing to note is the order of execution. As Jack noted in the comment, using document.write is frowned upon. This is true if your scripts are not located at the end of the html document as it will block the rendering of your webpage. I am not so sure, if this is still the case if your scripts are at the bottom though.

Nevertheless, you can still use a callback function to enforce order in the execution of javascript.

document.write() writes in the document where it is executed.
Whereas appendChild appends the element to the specified element.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!