Follow us on Facebook

Header Ads

Set Expire Headers for External JavaScripts Including Google Analytics

Set Expire Headers for External JavaScripts Including Google Analytics
Set Expire Headers for External JavaScripts Including Google Analytics


In this article, we will understand how will we add expire headers for the external scripts to minimize the loading time. The following tactic will make sure your website keeps loading fast without sacrificing any flexibility.

Every webmaster or blogger uses external/third-party JavaScript files for additional features/functions. For example, Google Analytics code to trace website visitors, AdSense or Buy Sell ads external JavaScript. It is  recommended to add expire headers for every types of files to leverage browser caching and speed optimization. Though, it is really hard to add expire headers for external scripts.

The Problem with External JavaScript Files

Honestly, using external JS files aren't problem per se. And, we definitely don't have any control on files that are hosted on third party servers. The problem arises when we want to set an expire header and optimize website speed.

The Solution: Adding Expire Headers to External Scripts


Step - 1: We will list all the external javascript file path that we are using on our website. In case of Google Analytics, the external JS would be:

<script type="text/javascript" src="https://ssl.google-analytics.com/ga.js"></script>

JS >> https://ssl.google-analytics.com/ga.js

Step - 2: The next step is to create a .php file. Let’s call it externaljs.php. Add the following code in it.

<?php
$files = array(
    'ga.js' => 'https://ssl.google-analytics.com/ga.js',
    'bsa.js' => 'https://s3.buysellads.com/ac/bsa.js',
    'pro.js' => 'https://s3.buysellads.com/ac/pro.js'
);
if(isset($files[$_GET['file']])) {
    if ($files[$_GET['file']] == 'ga.js'){
        header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + ((60 * 60) * 48))); // 2 days for GA
    } else {
        header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60))); // Default set to 1 hour
    }
    echo file_get_contents($files[$_GET['file']]);
}
?>

Note: You have to adjust the above PHP code and enter the path of external scripts. Once done, just upload it to the server.

Step - 3: Replace the external JavaScript call and replace it with a call to your externaljs.php. Here is the example

<script type="text/javascript" src="externaljs.php?url=ga.js"></script>

And you’re done. You can now dynamically import external .js file on your server and, therefore, set the right expire header for each script.

Post a Comment

0 Comments