The async and defer attributes for the <script> element have nice support now, so it’s time to learn exactly what they do!
Legend
<script>
Let's begin by process what <script> with none attributes will. The HTML file are parsed till the script file is hit, at that time parsing can stop and a call for participation are created to fetch the file (if it's external). The script can then be dead before parsing is resumed.
<script async>
async downloads the file through out HTML parsing and can pause the HTML program to execute it once it'sfinished downloading.
<script defer>
defer downloads the file throughout hypertext markup language parsing and can solely execute it once the computer program has completed. defer scripts also are guarenteed to execute within the order that they seem within the document.
When should I use what?
Typically you would like to use async wherever attainable, then defer then no attribute. Here area unit some general rules to follow:
If the script is modular and does not rely on any scripts then useasync.
If the script relies upon or is relied upon by another script then usedefer.
If the script is small and is relied upon by anasync script then use an inlinescript with no attributes placed above the async scripts.
Support
IE9 and below have some pretty unhealthy bugs in their implementation of defersuch that the execution order isn't guarenteed. If you would like to support <= IE9 i like to recommend not exploitation defer in the least and embrace your scripts with no attribute if the execution order matters. Read the specifics here .
This time I will give functions.php custom to automatically defer or async javascript (js).
Function: adding async = "async" for async and defer = "defer" to defer javascript (js).
defer
add_defer_attribute function ($ tag, $ handle) { // add script handles to the array below $ Scripts_to_defer = array ( 'my-js-handle', 'another-handle');