Auto Defer Or Async Javascript in Wordpress
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 use
async
. -
If the script relies upon or is relied upon by another
script then use
defer
. -
If the script is small and is relied upon by an
async
script then use an inlinescript
with no attributes placed above theasync
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 .
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'); foreach ($ scripts_to_defer as $ defer_script) { if ($ defer_script === $ handle) { return str_replace ( 'src', 'defer = "defer" src ", $ tags); } } return $ tag; }
add_filter ( 'script_loader_tag', 'add_defer_attribute', 10, 2);
async
add_async_attribute function ($ tag, $ handle) { // add script handles to the array below $ Scripts_to_async = array ( 'my-js-handle', 'another-handle'); foreach ($ scripts_to_async as $ async_script) { if ($ async_script === $ handle) { return str_replace ( 'src', 'async = "async" src ", $ tags); } } return $ tag; }
add_filter ( 'script_loader_tag', 'add_async_attribute', 10, 2);
Let me know if you have any questions below.
Comments
Post a Comment
Bila Ada posting yang kurang, atau error atau yang lainnya, silahkan tinggalkan komentar agar artikel/post di perbaiki.
Jangan Lupa Cek Box "Notify Me" agar tahu komentar kamu dibalas oleh saya.
If there are any posts that are missing, or error or anything else, please leave a comment for the article / post to be fixed.
Do not Forget Check Box "Notify Me" to know our comments replied by me.