Can i use defer attribute in inline js?

Issue

    <!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?

Solution

It’s not possible. Per MDN:

defer: This attribute must not be used if the src attribute is absent (i.e. 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

Answered By – CertainPerformance

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.