How To Defer Loading Of Scripts In WordPress

By April 19, 2017Blog, CMS, Wordpress
WordPress Tutorials by Allure Web Solutions

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 jquerywp_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);
Mike Doubintchik

Author Mike Doubintchik

More posts by Mike Doubintchik

Join the discussion 6 Comments

  • Pradeep says:

    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 says:

    How would i exclude analytics.js from the code above?

    • Mike Doubintchik says:

      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

  • Pradeep says:

    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.

Leave a Reply