How to Add an Expired Header for Google Analytics

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.

Woman posing with laptop computer
Keep users happy by tweaking Google Analytics for speed.
credit: Jupiterimages/Comstock/Getty Images

Step

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

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

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:

Step

Header set Expires "Thu, 21 Apr 2016 20:00:00 GMT"

Step

Change the date above to a date far in the future.

Step

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."