JavaScript Async Load for WordPress Enqueued Scripts

All WordPress themes use JavaScript to create sliders and other nice features. Even plugins add JavaScript to blog pages, for example Akismet adds a little piece of code, bbPress adds code for the editor. The standard WordPress themes add a script to manage the comment replies.

All that scripts must be downloaded and most of the time they are “blocking” resources. That means the browser must download them to show the page. But most of them are not need to display the page, only to interact with the user actions.

So they could be downloaded after the page has been rendered: it’s a part of the web performance issues.

All modern browser accept an indication to download those script “later” or asynchronously. But scripts are usually added with a WordPress standard system, named script queuing. This is a good practice since it avoids duplicates and conflicts.

WordPress does not allow to add an “async” directive┬áto the queued script, so they are always blocking resources to download.

Asynchronous loading is useful but must be used with care for a series of technical reasons. But stated you are a diligent coder, you could add selectively an “async” to script that can effectively loaded in this fashion.

To compensate this gap of WordPress I added to Header and Footer a nice feature: you can list a series of script (by WordPress handle name) that must be force to be async. Using it with care, you can improve the loading experience of your blog web pages and get a better rank on page speed tools.

Which script to load asynchronously is up to you, but Header and Footer helps in finding the handle names: activating the debug feature and looking at the page source, before every script there is an HTML comment with its handle name.

Surely you would make async the “comment-reply” script, the “akismet-form” and the
“admin-bar”. I left the list of handles empty to avoid problems, since every theme is different.

Note that you must not add “jquery” as asynchronous!

There are many other script that cannot be loaded in async mode, so you should eventually make experiments.

Two final words: WordPress should support the async directive, second the coders should write JavaScript library that can be loaded asynchronously.

 

My excuses for my bad english but it's the only way I have to communicate with you. Would you suggest a correction? Leave a comment, thank you!

Leave a Reply