How to Add an Expired Header for Google Analytics

By Michael Cox

Although Google Analytics can help you to precisely track your website traffic, the JavaScript code it uses can slow down your site. Performance analysis services like Yahoo! Yslow may suggest you add an Expires header to allow browsers to cache this code. Unfortunately, Expires headers do not apply to content served from third-party sites, and Google does not recommend serving its Analytics JavaScript locally. However, there are steps you can take to speed up Google Analytics so your site loads faster.

Things You'll Need

  • An existing Google Analytics account

Step 1

Use the asynchronous Google Analytics tracking code snippet, which enables other elements to continue loading even when Google's JavaScript is slow to load. To find the asynchronous code snippet for your site, sign in to Google Analytics and click the gear symbol at the upper right of the page; then choose your site and click "Tracking Code." Choose the appropriate settings for your site, then copy the snippet and use it to replace your site's older Google Analytics code.

Step 2

Place the Google Analytics code at the bottom of your pages between the closing tag and the closing tag so that each page will load before asking for the remote JavaScript code. If you use this method, Google may not count visitors to your site who close or stop loading the page before the code loads.

Step 3

Store the Google Analytics JavaScript code on your local server using a shell script to direct your pages to the local code and a cron job to keep the code up-to-date. You can then add the following code to your .htaccess file to cache the code in users' browsers:Header set Expires "Thu, 21 Apr 2016 20:00:00 GMT"Change the date above to a date far in the future.This method requires competence in implementing scripts and should be used only as a last resort if you can trace site speed problems directly to your Google Analytics code despite trying other solutions. For shell script examples, see "Resources."

Tips & Warnings

  • The Google Analytics JavaScript code includes its own Expires header, set to two weeks from the most recent access. Because Google Analytics code appears on so many websites, users will often already have the code cached when they view your site.