Sunday, December 13, 2015

Parser blocking JavaScript


Why is javascript parser blocking?

When the browser encounters "<script> " it has to pause DOM construction.The reason, the script reference might try to access the css properties.

Assume a scenario where the postman comes with a letter and he has to wait for the Gate to open. He cannot deliver the letter till the gate is open




Solution:

  • inline java script. 
      Note:With this approach we would end up with redundant code
  •  Load javascript after onload event

<script type="text/javascript">
function deferOnload() {
var element = document.createElement("script");
element.src = "defer.js";
document.body.appendChild(element);
}
if (window.addEventListener)
window.addEventListener("load", deferOnload, false);
else if (window.attachEvent)
window.attachEvent("onload", deferOnload);
else window.onload = deferOnload;
</script>
  • Deferred loading by moving javascript reference to the bottom
       Note: We might have to have script reference at the top
        ex: Google analytics
  • Deferred execution with "async "   .It tells the browser that it does not have to block DOM construction when it encounters script tag and it does not block on CSSOM
<script src="demo_async.js" async></script>

No comments:

Post a Comment