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
1 2 3 4 5 6 7 8 |
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 ); } |
I am a full-stack developer. My expertise include:
I love programming, design and know my way around server architecture as well. I would never feel complete, with one of these missing.
I have a broad range of interests, that’s why I constantly dive into new technologies and expand my knowledge where ever required. Technologies are evolving fast and I enjoy using the latest.
Apart from that, I am a peace loving guy who tries to have people around him that think the same. I truly believe in the principle: “If you help someone, someone will help you, when you need it."