0
votes

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 ?

1
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 practiceHuangism
@Huangism so are you saying this structure has no render blocking scripts ?Mayur Arora
If your page only has one container like that, it really doesn't make much difference. But there is nothing wrong using deferHuangism
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 . @HuangismMayur Arora
It gives you the perception of things loading faster, but it might block user interaction you can take a look stackoverflow.com/questions/30653081/… 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 loadingHuangism

1 Answers

0
votes

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.