The Ultimate Guide to Moving JavaScript to the Footer in WordPress (2023)

Hey there, WordPress user! Are you frustrated with slow-loading pages and low Google PageSpeed scores? I feel your pain. As a WordPress developer who‘s spent countless hours optimizing sites, I can confidently say that one of the most effective changes you can make is moving JavaScript files to the footer.

In this ultimate guide, I‘ll dive deep into why this technique works and show you step-by-step how to implement it on your own WordPress site. So grab a coffee, settle in, and let‘s get your site loading lightning-fast!

Why Page Speed Matters

Before we jump into the technical details, let‘s talk about why you should even care about page speed in the first place.

The truth is, we‘re living in an age of instant gratification. If your website doesn‘t load within a few seconds, visitors will hit the back button and move on to your competitor. Don‘t believe me? Check out these eye-opening statistics:

  • 47% of consumers expect a webpage to load in 2 seconds or less (Source)
  • A 1-second delay in page response can result in a 7% reduction in conversions (Source)
  • 75% of users would not return to websites that took longer than 4 seconds to load (Source)

In other words, a slow website can directly impact your bottom line. Plus, search engines like Google use page speed as a ranking factor, so faster sites tend to appear higher in search results.

How Web Pages Load

To understand why moving JavaScript to the footer can speed up your WordPress site, we need a quick primer on how web pages are loaded and rendered.

When a visitor lands on your page, their browser sends a request to your web server for the page‘s HTML. The server sends back the HTML content, which the browser parses from top to bottom.

As the browser encounters external resources like stylesheets, scripts, and images, it sends additional requests for those files. Some resources, like images, can load simultaneously. But others, like JavaScript files, are loaded synchronously by default. That means the browser halts rendering until the script is downloaded and executed.

If you have JavaScript files in the <head> of your page, they will delay the loading of your content. Visitors will see a blank white screen until the scripts finish loading, even if the actual page content is ready to be displayed.

By moving JavaScript files to the end of your page, just before the closing </body> tag, you allow the browser to load and render the visible content first. Then it can download and process the scripts in the background without blocking the rest of the page.

Finding Scripts to Move

Now that you understand the why, let‘s talk about the how. The first step is identifying which JavaScript files your WordPress site is loading in the first place.

Using Browser Developer Tools

The easiest way to find scripts is to use your browser‘s built-in developer tools. In Chrome or Firefox, right-click on a page and choose "Inspect" or "Inspect Element". Then switch to the "Network" tab and reload the page.

You‘ll see a list of all the files the page loads, including HTML, CSS, JavaScript, and images. Filter the list by clicking the "JS" button to show only scripts.

For each script, you‘ll see which domain it‘s loaded from and the file path. This will give you clues as to whether the script belongs to WordPress core, a theme, or a plugin.

You can also click on a script filename to see its source code and check if it‘s already being loaded in the footer. Look for lines like wp_enqueue_script( ..., true ) where true means the script is being loaded in the footer.

Checking the Page Source

Another way to find scripts is to view the page source. Right-click the page and choose "View Page Source" (or press Ctrl+U in Chrome).

Search for <script in the page source to see all the script tags. Note where each one is located in the document. Scripts in the <head> or <body> are being loaded in the header, while those just before </body> are already in the footer.

You can also search for the script filename to find where it‘s being added by a theme or plugin. For example, if you see a script at https://example.com/wp-content/plugins/some-plugin/js/script.js, you know it belongs to the "some-plugin" plugin.

Using a Plugin

If you‘re not comfortable digging through code, you can use a plugin like Asset CleanUp to see which scripts each plugin and theme are loading on a page. It adds an "Asset CleanUp" menu under each post, page, and custom post type where you can view all the enqueued scripts.

Asset CleanUp also lets you selectively disable scripts on a per-page basis, which can be helpful for troubleshooting and optimization. But be careful not to break anything!

How to Move JavaScript to the Footer

Once you‘ve identified the scripts you want to move, there are a few different ways to relocate them depending on how they‘re being added to the page.

Method 1: Properly Enqueue Scripts

The proper way for themes and plugins to add scripts in WordPress is to enqueue them using the wp_enqueue_script function. This ensures scripts are loaded efficiently and in the right order.

Here‘s what a proper enqueue call looks like:

function myplugin_enqueue_scripts() {
    wp_enqueue_script(
        ‘myplugin-script‘,
        plugins_url( ‘js/script.js‘, __FILE__ ),
        array( ‘jquery‘ ),
        ‘1.0‘,
        true
    );
}
add_action( ‘wp_enqueue_scripts‘, ‘myplugin_enqueue_scripts‘ );

The key part is the last argument, true, which tells WordPress to load the script in the footer.

If your theme or plugin is already enqueueing scripts the right way, you can simply add true as the last argument to move the script to the footer.

If the script is being added directly with a <script> tag in a template file, you‘ll need to replace that with a proper wp_enqueue_script call like the one above in the theme‘s functions.php file or the plugin‘s main PHP file.

Method 2: Use a Plugin

If you can‘t or don‘t want to edit a theme or plugin directly, you can use a plugin like Speed Booster Pack or WP Rocket to automatically move scripts to the footer.

These plugins have options to either move all scripts to the footer or let you choose specific ones. They work by capturing the script tags and moving them to the end of the HTML document before it‘s sent to the browser.

Keep in mind that these plugins can‘t always catch scripts that are hardcoded directly into template files. But they‘re a good solution if you want a quick fix without messing with code.

Method 3: Edit Plugin and Theme Files

If you can‘t use a plugin and you‘re comfortable editing PHP, you can modify a theme or plugin‘s code directly to move its scripts to the footer.

I only recommend this method as a last resort because your changes will be overwritten if the theme or plugin is updated. But if you must, here‘s how:

First, find the script tag or wp_enqueue_script call in the theme or plugin‘s PHP files. If it‘s a proper enqueue, simply add true as the last argument to move it to the footer.

If it‘s a bare <script> tag, you‘ll need to replace it with a wp_enqueue_script call in the appropriate hook, usually wp_enqueue_scripts. Refer to Method 1 above for an example.

Again, make sure to thoroughly test your changes and consider using a child theme or custom plugin instead of editing core files directly.

Advanced Script Loading Techniques

In addition to moving scripts to the footer, there are a couple other techniques you can use to load JavaScript more efficiently.

Async Loading

The async attribute tells the browser to download the script asynchronously in the background without blocking page rendering. The script will execute as soon as it finishes downloading, regardless of where it appears in the page.

To load a script asynchronously, add async to the <script> tag like this:

<script async src="script.js"></script>

Or in PHP:

wp_enqueue_script( ‘myplugin-script‘, plugins_url( ‘js/script.js‘, __FILE__ ), array(), ‘1.0‘, true );
wp_script_add_data( ‘myplugin-script‘, ‘async‘, true );

Keep in mind that async scripts can execute in any order, so only use async for scripts that don‘t depend on each other.

Defer Loading

The defer attribute is similar to async, but it guarantees the script will execute in the order it appears on the page. Deferred scripts won‘t run until the page is finished parsing.

To defer a script, add defer to the <script> tag:

<script defer src="script.js"></script>

Or in PHP:

wp_enqueue_script( ‘myplugin-script‘, plugins_url( ‘js/script.js‘, __FILE__ ), array(), ‘1.0‘, true );
wp_script_add_data( ‘myplugin-script‘, ‘defer‘, true );

Defer is a good choice for scripts that rely on the DOM being fully loaded and that don‘t need to run immediately.

The Impact of HTTP/2

It‘s worth noting that with the widespread adoption of the HTTP/2 protocol, some of the traditional advice around loading scripts has changed.

HTTP/2 allows multiple requests to be sent in parallel over a single connection, which reduces the impact of loading many small files. It also prioritizes requests so that critical resources like CSS and JavaScript can be loaded first.

With HTTP/2, the performance difference between loading scripts in the header versus the footer may be less noticeable. In fact, inlining small scripts in the HTML can actually be faster than making a separate request for them.

That said, moving render-blocking scripts to the footer is still a good practice for improving perceived performance and compatibility with older browsers. But it‘s not the only factor to consider in the age of HTTP/2.

To see if your server supports HTTP/2, you can use a tool like KeyCDN‘s HTTP/2 Test. If it does, consider reevaluating your script loading strategy and prioritizing other optimizations like minification, compression, and caching.

Other Ways to Speed Up WordPress

Moving JavaScript to the footer is just one piece of the performance puzzle. Here are a few other techniques you can use to speed up your WordPress site:

  • Optimize images by compressing them and serving them in next-gen formats like WebP
  • Minify CSS and JavaScript files to reduce their size
  • Combine small files to reduce HTTP requests
  • Use a content delivery network (CDN) to serve static assets
  • Enable browser caching and Gzip compression
  • Lazy load images and videos
  • Clean up your WordPress database and disable unused features and plugins
  • Upgrade to a faster web host or dedicated server

For more tips, check out the WordPress Codex‘s Performance page and our Ultimate WordPress Speed Guide.

Frequently Asked Questions

Q. Will moving JavaScript to the footer break my site?
A. It depends on the script. Some scripts rely on being loaded in the header, like analytics tracking codes or certain jQuery plugins. Always test your site thoroughly after making changes to your script loading.

Q. Can I move all scripts to the footer?
A. Not necessarily. Some scripts need to be loaded in the header to function properly. A good rule of thumb is to move scripts that don‘t affect the visible content or user interaction to the footer, while leaving critical scripts in the header.

Q. How do I know if a script is safe to move?
A. The best way is to test it. Use your browser‘s developer tools to see if moving the script causes any errors or breaks functionality. You can also check the script‘s documentation or ask the plugin or theme author if you‘re unsure.

Q. What if I can‘t move a script to the footer?
A. If a script needs to be loaded in the header, you can still optimize it by minifying it, combining it with other scripts, or loading it asynchronously using the async or defer attributes.

Conclusion

Moving JavaScript files to the footer is one of the most effective ways to speed up your WordPress site and improve your Google PageSpeed scores. By loading scripts at the end of the page, you allow the browser to display content sooner while scripts are downloaded and executed in the background.

To move scripts to the footer, you can either enqueue them properly in your theme or plugin files, use a helper plugin like Speed Booster Pack, or edit the code directly as a last resort.

Remember to thoroughly test your changes and consider other optimization techniques like minifying files, lazy loading, and caching.

With a little effort and the right tools, you can achieve a lightning-fast WordPress site that delights your visitors and dominates your competitors in search rankings. So what are you waiting for? Get out there and start optimizing!

Did you like this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.