Using the defer attribute HELP PLEASE

Using the defer attribute HELP PLEASE
0

#1

Does anyone have any experience using the defer attribute in script? I am having trouble making it work.

When I load the below code in browser the html is not loading before script, as I would like it to. Please help.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Hey</title>
    <script src="main.js" defer></script>
  </head>
  <body>
    <div>Hi</div>
</body>
</html>

#2

I haven’t used it but i would have placed the script tag before </body> to load the content before the js file with defer and make sure main.js is in the same folder since you have directly called the js file


#3

What are you expecting it to do? The HTML is totally fine, but without knowing what the JS you’re trying to execute is supposed to be doing, can’t see what is/isn’t happening.


#4

Thanks for replying guys! Sujith3021, I tried what you suggested as well but it did not do what I wanted it to do still. From what I understand DanCouper, when using the defer attribute inside the script, all markup should be rendered before javascript loads, if the defer attribute is included in the script.

My src link just makes an alert box with a message and OK button display, which is what I want and that’s working, however, the markup does not load first, as I thought it was supposed to when the defer attribute is included in the script.

I thought maybe this was due to my browser but its not working on all browsers I try… so I’m just confused why its not working.


#5

Can you try a test using console.log rather than alert?


#6

I think this attribute only executes on certain browsers. I tried it on Firefox and it now works. Safari and Chrome did not work.


#7

Both of those should work perfectly; this isn’t some browser-specific API, these are just standard HTML5 attributes. How are you testing this: how can you tell that the script is loading before the HTML, and what does the script file contain?


#8

I am testing this by opening my html file, created in a editor, in my browser. When I opened it on Safari and Chrome, the alert dialog box opened up before my html ‘parsed’ (if I am using that term correctly). I have to select the Ok button on the alert box first, then html parses. But when I opened it on FireFox in contrast, the html parses first before the alert box comes up.


#9

It is recommended that you don’t use defer or async unless you are absolutely certain (their behavior depends on varying implementation). Often, it is far better to include the script tag just before the end of the body or use window.onload(). Since you mentioned the first option doesn’t work, try the second.

There is also possibility that your JS code is incorrect. So, you may want to post the JS code as well.