0

I ran my web page on the Google web page test tool and it suggested I use 'defer' or 'async' attribute to get rid of render blocking JS . My HTML is this:

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My Page</title>
    <link href="https://mycdn.com/style.css" rel="stylesheet">
</head>

<body>
    <div id="app-container"></div>
    <script type="text/javascript" src="https://mycdn.com/shared.js"></script>
    <script type="text/javascript" src="https://mycdn.com/main.js"></script>
</body>

</html>

Since , my scripts are getting including before the closing of the 'body' tag , and not in the 'head', are they really blocking ? Would a paint not happen until the closing 'html' is parsed ?

Mayur Arora
  • 447
  • 5
  • 11
  • Google probably also tells you to use THEIR compression tool while MS tells you to use THEIR compression tool. Blocking or not, they just want you to use what they think is best practice – Huangism Mar 05 '18 at 17:46
  • @Huangism so are you saying this structure has no render blocking scripts ? – Mayur Arora Mar 05 '18 at 17:53
  • If your page only has one container like that, it really doesn't make much difference. But there is nothing wrong using defer – Huangism Mar 05 '18 at 17:56
  • I know I can use defer and it will not make a difference . I am actually trying to understand if this structure really blocks rendering . @Huangism – Mayur Arora Mar 05 '18 at 17:58
  • It gives you the perception of things loading faster, but it might block user interaction you can take a look https://stackoverflow.com/questions/30653081/why-scripts-at-the-end-of-body-tag your content will be visible to users earlier so the scripts at the bottom allows that, in my opinion, it is not blocking your dom content, but if you have interactions in the js, then obviously those will only work after the js is done loading – Huangism Mar 05 '18 at 18:15

1 Answers1

0

Using async or defer or moving your scripts to the bottom of the file does not always work across different browser, one recommended way of loading the external scripts is to load it in the following way is by placing this piece of code before the end of the body tag.

<script type="text/javascript">
  function downloadJSAtOnload(){
    var element = document.createElement("script");
    element.src = "defer.js"; // Replace "defer.js" with your url or filename
    document.body.appendChild(element);
  }
  if (window.addEventListener) window.addEventListener("load", downloadJSAtOnload, false);
  else if(window.attachEvent) window.attachEvent("onload", downloadJSAtOnload);
  else window.onload = downloadJSAtOnload;
</script>

See here for more.

Tim Han
  • 166
  • 1
  • 12
raxerz
  • 516
  • 4
  • 10
  • @time-han What I really am keen on getting to know is, if ,with my HTML, the scripts at the bottom are blocking. – Mayur Arora Mar 06 '18 at 04:43