Skip to content

Instantly share code, notes, and snippets.

@bebaps
Last active June 2, 2017 16:10
Show Gist options
  • Save bebaps/20c498e619aa172e40737e60b9d3e83d to your computer and use it in GitHub Desktop.
Save bebaps/20c498e619aa172e40737e60b9d3e83d to your computer and use it in GitHub Desktop.
Manually defer the parsing of JS files in WordPress. Depending on the theme and installed plugins, it may be better to let a plugin handle this.
<?php
/**
* Defer all JS files
*
* @method defer_parsing_of_js
* @param String $url The URL of the script
* @return String The "cleaned" URL, including the additional defer attribute
*/
function defer_parsing_of_js( $url ) {
// If the URL is not of a .js file, just return it
if ( false === strpos( $url, '.js' ) ) {
return $url;
}
// If the URL is for jQuery, just return that also
if ( strpos( $url, 'jquery.js' ) ) {
return $url;
}
// Otherwise, return the URL plus the defer attribute. The onload is really just a hack to get the URL to close properly
return "{$url}' defer onload='";
}
// Only defer the JS when viewing the front end of the site
if ( !is_admin() ) {
add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment