Sometimes we may want to defer loading of scripts for a wide variety of uses. In WordPress we enqueue scripts in our functions.php file (or somewhere else depending on your theme structure). Below are two functions that go into your functions.php file that add the defer
attribute to your scripts.
Defer Scripts By Handle
The handle is the name of your script and the first argument of the wp_register_script
or wp_enqueue_script
functions. For example the handle is jquery: wp_register_script('jquery', ('//cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'), false, null, true);
/** * * Defer scripts by handle * * @param $tag * @param $handle * @return mixed */ function add_defer_attribute($tag, $handle) { // add script handles to the array below $scripts_to_defer = array('jquery', 'handle-2'); foreach($scripts_to_defer as $defer_script) { if ($defer_script === $handle) { return str_replace('></script>', 'defer></script>', $tag); } } return $tag; } add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);
Defer All Scripts
/** * * Defer all scripts * * @param $tag * @return mixed */ function add_defer_attribute($tag) { if (!is_admin()) return str_replace('></script>', 'defer></script>', $tag); return $tag; } add_filter('script_loader_tag', 'add_defer_attribute', 10, 2);
Does this negatively impact Google Analytics? In the sense, will it cause Google Analytics to show less users on my site than are “actually” there?
@Pradeep
I found a pretty thorough answer to your question: http://stackoverflow.com/a/32173380/3602355
If you use the first script in this blog post, you can select directly which enqueued scripts to defer.
How would i exclude analytics.js from the code above?
There are two codes above, which one are you referring to?
Which method are you using to add the analytics.js script?
– Enqueueing with WordPress function
– Including analytics.js file into html with
script src=
– Hardcoding the actual script into the html
We’re using the Defer All Scripts Method above, added to functions.php.
The website is [website URL redacted] and we’ve added Analytics.js as a Text Widget in the Sidebar.
That script is not deferred since you hardcoded into the page. You are all set.