13
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

インラインscriptのdefer, async属性は無効

Posted at

以下のように、インラインのscriptにもdefer属性付ければ、headでdefer属性付けたscriptより後に実行してくれること期待したけど、ダメでした。

functions.js
function awesomeFunction (selector) {
  document.querySelector(selector).innerHTML = 'awesome!!';
}
<html>
  <head>
    <script src="functions.js" defer></script>
  </head>
  <body>
    <div id="app"></div>
    <script defer>
      awesomeFunction('#app');
    </script>
  </body>
</html>

インラインscriptのdefer, async属性は意味無しだそうです😢
https://developer.mozilla.org/ja/docs/Web/HTML/Element/Script#Attributes

おとなしくdocument.addEventListener('DOMContentLoaded', ...書くしかない

<html>
  <head>
    <script src="functions.js" defer></script>
  </head>
  <body>
    <div id="app"></div>
    <script>
      document.addEventListener('DOMContentLoaded', function () {
        awesomeFunction('#app');
      });
    </script>
  </body>
</html>
13
5
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
13
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?