Javascript - Page Speed Best Practices
Take care not to block page rendering when you need to include JavaScript in pages.
Before the browser can render a page it has to build the DOM tree by parsing the HTML markup. During this process, whenever the parser encounters a script it has to stop and execute it before it can continue parsing the HTML. In the case of an external script the parser is also forced to wait for the resource to download, which may incur one or more network roundtrips and delay the time to first render of the page.
Avoid render-blocking JavaScript
External JavaScript should be included on pages in a way that doesnβt block page rendering. A <script src="…">
tag will block HTML rendering until the JavaScript file specified is fetched and the contents of the file has finished executing. Inline JavaScript also blocks rendering until execution is complete. You can stop <script>
tags from blocking rendering by placing them directly before the closing </body>
tag. Alternatively, for external JavaScript files you can load the script in the background using either 1) <script defer src="…">
, which delays script execution until the DOM is ready or 2) <script async src="…">
, which will execute the script as soon as it has loaded. Note that defer
scripts execute in the order they appear on the page like inline scripts. However, async
scripts execute whenever they have downloaded so their execution order can change. This difference is important when scripts have dependencies.
Learn more
- Remove Render-Blocking JavaScriptdevelopers.google.com
- Adding Interactivity with JavaScriptdevelopers.google.com
- Put Scripts at the Bottomdeveloper.yahoo.com
Avoid excessive inline JavaScript
Avoid inline JavaScript to improve page rendering times and caching efficiency. JavaScript code can be inlined directly into pages with the <script>
tag which can be convenient during development but comes with the downsides that 1) inline Javascript will block HTML rendering until the JavaScript code is parsed and executed and 2) if the code is shared between pages it wonβt be cached. You should instead include JavaScript as external files with <script src="…">
tags in a way that defers loading. However, inlining small scripts can be benefitial when avoiding an extra request is more important for performance than caching. We recommend each page should not exceed more than 10,000 bytes of inline JavaScript.
Learn more
- Best Practices for Speeding Up Your Web Sitedeveloper.yahoo.com
- Remove Render-Blocking JavaScriptdevelopers.google.com
More articles in this series
β This article is from our comprehensive Page Speed Best Practices guide.
β Next article in this series: Redirects
β Previous article in this series: CSS