When the defer attribute is present in the script tag, it specifies that the script is executed when the page has finished parsing. A requirement that is enforced by Google for example (Page-Speed ranking).
Currently the WordPress wp_enqueue_script provides no easy way to add new attributes, but there is a way around that :)
The below hack / filter needs to be added to your theme function.php. The filter should be your preferred solution, as the clean_url filter has been deprecated.
Make sure that your website / theme is still loading after adding these changes. If needed you can add more exceptions, as I did for jQuery.
Hack for WordPress before 4.1
|
if(is_admin() === FALSE){ function defer_parsing_of_js ( $url ) { if ( FALSE === strpos( $url, '.js' ) ) return $url; if ( strpos( $url, 'jquery.js' ) ) return $url; return "$url' defer "; } add_filter( 'clean_url', 'defer_parsing_of_js', 11, 1 ); } |
Filter for WordPress 4.1+
Updated: 26.04.2015 – using clean Regexp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
if(is_admin() === FALSE){ function add_js_defer($tag, $handle, $src){ if( strpos( $tag, 'jquery.js' ) ) return $tag; preg_match_all('/([\w\-.:]+)\s*=\s*("[^"]*"|\'[^\']*\'|[\w\-.:]+)/i', $tag, $match); $newtag = "<script "; foreach($match[1] as $key=> $val){ $newtag .= $val."=".$match[2][$key]." "; } $newtag .= "defer></script>"; return $newtag.PHP_EOL; } add_filter( 'script_loader_tag', 'add_js_defer', 11, 1 ); } |
Browser Support
- All modern browsers
- Support in IE9 is flaky, as the execution order isn’t guaranteed.
- Can I use