LoginSignup
1
1

More than 3 years have passed since last update.

document.writeの動作について

Posted at

概要

document.writeは非推奨扱いになっていますが、GTAで使用してあったので動作検証してみました。

検証手順

document.writeとinsertAdjacentElement(挿入位置を指定するため)でscriptタグをDOMに挿入する。
挿入されたJSの実行順序を確認する。

HTML

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <script>console.log('header!')</script>
</head>
<body>
    <script type="text/javascript" src="./js/first.js"></script>
    <script>
        console.log('after script');
    </script>
    <img src="../masuo.jpeg" alt="masuo-san">
</body>
</html>

読み込まれるfirst.jsからsecond.jsを読み込みます。

first.js(insertAdjacentElement)
(() => {
    console.log('first');

    const second = document.createElement('script');
    second.id = 'second';
    second.src="./js/second.js";
    second.type = 'text/javascript';

    const first = document.getElementById('first');
    first.insertAdjacentElement('afterend', second);
})();

console.log('first out');
first.js(document.write)
(() => {
    console.log('first');

    document.write('<script id="second" type="text/javascript" src="./js/second.js"></script>');
})();

console.log('first out');
second.js(insertAdjacentElement)
(() => {
    console.log('second');

    const third = document.createElement('script');
    third.type = 'text/javascript';
    third.innerText = `console.log('third inline');`;

    const second = document.getElementById('second');
    second.insertAdjacentElement('afterend', third);
})();

console.log('second out');
second.js(document.write)
(() => {
    console.log('second');

    document.write('<script id="third" type="text/javascript">console.log("third inline");</script>');
})();

console.log('second out');

結果

insertAdjacentElement

Screen Shot 2019-12-06 at 10.08.17.png

document.write

Screen Shot 2019-12-06 at 10.10.09.png

考察

  • JavaScriptファイルの読み込みは非同期になるので、特別な指定をしなければ読み込んだ時点で実行される。

  • そのためinsertAdjacentElementは元々インラインで書かれていたScriptの後に実行されている。

  • 一方でdocument.writeは挿入したscriptが即時実行されている → jsファイルの読み込み・実行までブロックしている

ご指摘等ありましたら、ご連絡下さい。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1