I have various javascripts that are necessary plugins in one of my WordPress domains, and I know where in the php file it's called from.
I'm taking every measure I can take to speed up page loading times, and every speed tester on the web says to defer javascripts if possible.
I have read about the defer='defer' and the async functions in javascript and I think one of these will accomplish what I'm trying to accomplish. But I'm not understanding how I'd do so in a php file.
For instance, here is a snippet from one particular plugin's php file where the javascript file is being called:
function add_dcsnt_scripts() {
wp_enqueue_script( 'jquery' );
wp_enqueue_script( 'dcsnt', dc_jqsocialtabs::get_plugin_directory() . '/js/jquery.social.media.tabs.1.7.1.min.js' );
}
I've read that it's best to do something like this for faster page loading times:
<script defer async src="..."></script>
But I don't know how to accomplish that within a php file. I want to do this with all of my javascript files.
How would I accomplish deferring or asyncing this javascript snippet to is loads last and speeds up page load times? What would be the ideal way to increase page load times across all browsers? Thanks for any guidance anybody can offer!
Trying to keep things somewhat modular and all encompassing, the following approach dynamically chooses how to embed the tag with the async or defer attributes by just appending a small identifier to the $handle name:
Example usage:
Outputs:
Thanks to @MattKeys @crissoca for inspiring my answer here.
Very little modification code Mike Kormendy, which allows you to add 2 attributes at once:
Result:
Or more universal way:
so you can add async to any script without code changes, just add #asyncload to script url as:
Something to add the
clean_url
filter solution, make sure to validate to use it only on the font-end maybe usingif( ! is_admin() ){}
popular plugins like ACF might give you a headache.Update
Here is my modified version of the solution:
To gain control over which js files to defer and avoid conflicts you can append a variable to the url in the wp_register_script function like below.
Then change the line:
To:
The new filter looks like this.
I believe it's bad practice to defer/async WordPress jQuery. Better solution would be to exclude jQuery from the filter:
You can use
defer
instead ofasync