简体   繁体   中英

Can i use defer attribute in inline js?

    <!doctype html>
    <head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js" defer></script>
     <script defer> // Can I use defer atttribute here?
           //Inline js code 
    </script>
    </head>
    <body> 

    </body>
    </html>

Here can I use defer attribute to inline JS?

It's not possible. Per MDN :

defer : This attribute must not be used if the src attribute is absent (ie for inline scripts), in this case it would have no effect.

For the functionality you want, you'll have to do one of the following:

  • Put the script into a separate file and set a src
  • Put the inline script at the end of the <body>
  • Wrap the whole code of the script inside a DOMContentLoaded listener

No

The defer attribute is a boolean attribute.

When present, it specifies that the script is executed when the page has finished parsing. Note: The defer attribute is only for external scripts (should only be used if the src attribute is present).

You can refer this for more

The defer attribute has no effect on inline code. An alternative is using the type="module" attribute, which will defer the code execution:

<script type="module">
<!-- inline code-->
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM