利用第三方JS的浏览器缓存 [英] Leverage browser caching for 3rd party JS

查看:85
本文介绍了利用第三方JS的浏览器缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在httpd.conf上设置了有效期

I have set Expiry on my httpd.conf

ExpiresActive On
ExpiresDefault "access plus 1 month"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
ExpiresByType text/css "access plus 1 month"
ExpiresByType text/javascript "access plus 1 month"
ExpiresByType application/x-javascript "access plus 1 month"

这有助于浏览器缓存图像,字体文件,站点自己的css和js文件.但我的网站中也包含外部JS:

This helps with browser caching for images, fonts files, site own css and js files. But I also have external JS included in my website:

http://connect.facebook.net/en_US/sdk.js (20 minutes)
http://apis.google.com/js/client.js (30 minutes)
https://apis.google.com/js/rpc:shindig_random.js?onload=init (30 minutes)
https://platform.twitter.com/widgets.js (30 minutes)
https://www.google-analytics.com/analytics.js (2 hours)

Google Pagespeed Insights对上面的文件说: 在HTTP标头中为静态资源设置有效期限或最长期限,可指示浏览器从本地磁盘而不是通过网络加载以前下载的资源.

Google Pagespeed Insights says for the upper files: Setting an expiry date or a maximum age in the HTTP headers for static resources instructs the browser to load previously downloaded resources from local disk rather than over the network.

如何利用浏览器缓存此外部JS文件?有帮助吗?

How to leverage browser cache this external JS files ? Any Help ?

推荐答案

确实是一个令人讨厌的问题.恐怕没有一个像 那样容易修复的.但是您可以使用cron.

An annoying issue, Indeed. Not one that is as easily fixable I'm afraid. But what you can do is use a cron.

首先,请记住,Google不太可能因自己的工具(如Google Analytics(分析))而对您进行惩罚.但是,如前所述,可以使用cron对其进行修复,这基本上意味着您可以在本地加载JavaScript并提取更新的脚本.

Firstly, keep in mind that Google are very unlikely to penalise you for their own tools (Like Analytics). However, as mentioned before, it can be fixed using a cron, which basically means you load the JavaScript locally and pull updated scripts.

操作方法:

How to do this:

首先,您需要下载正在运行的脚本.我将以Google Analytics(分析)为例(这似乎是人们抱怨最多的问题脚本,但是您可以将其复制到任何外部脚本中.)

First of all, you need to download the script that you're running. I will be using Google Analytics as an example (this appears to be the most problematic script people complain about, but you can replicate this for any external scripts).

查找您的代码并找到脚本的名称,在我们的示例中为:google-analytics.com/ga.js.将该URL弹出到Web浏览器中,它将显示源代码.只需将其复制并保存为ga.js.

Look in your code and find the name of the script, in our case it is: google-analytics.com/ga.js. Pop this URL into your web browser and it will bring up the source code. Simply make a copy of it and save it as ga.js.

在我的情况下,将此新创建的JavaScript文件保存到您的网络服务器上:

Save this newly created JavaScript file onto your webserver, in my case:

- JS
  - ga.js

接下来,您将需要更新正在调用脚本的页面上的代码,而只需更改正在调用JavaScript文件的目录即可.再次以我们为例,我们将更改此行:

Next you will need to update the code on the pages that are calling your script and just change the directory that is calling the JavaScript file. Once again in our case, we will be changing this line:

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.yoursite.com/js/ga.js';

此时,您的网站现在将在您的网站 本地 中运行脚本!但是,这意味着脚本将永远不会更新.除非您每周重新运行此简短过程.那取决于你..但是我对此太懒了.

At this point, your site will now run the script from your website locally! However, this means the script will never update. Unless you re-run this short process every week. That is up to you.. but I'm far too lazy for that.

这是CRON发挥作用的地方:

This is where the CRON comes into play:

几乎每个托管服务都有一个选项供您设置cron作业.在Hostinger上,它位于您的主机面板上,在GoDaddy上,您可以在内容"选项下找到它.

Just about every single hosting service will have an option for you to set up cron jobs. On Hostinger it is on your Hosting Panel, on GoDaddy you will find it under the Content option.

将以下脚本放入cron中,您需要做的就是更改变量$localfile的绝对路径.该脚本的作用是从Google提取ga.js文件的更新脚本.您可以设置希望其运行该过程的频率的时间范围.从每小时一次到每月一次甚至更长时间.

Put the following script into your cron, and all you need to do is change the absolute path to the variable $localfile. What this script does is pull the updated script from Google for the ga.js file. You can set the time frame on how often you want it to run this process. Ranging from once every hour to once a month and beyond.

如果您还对除Google Analytics(分析)以外的外部文件执行此操作,则还需要更改变量$remoteFile.因此,$remoteFile是外部JavaScript文件的URL,而变量$localFile则将路径放置到新的本地存储文件中,就这么简单!

If you're also doing this for external files other than Google Analytics, then you will also need to change the variable $remoteFile. So $remoteFile is the URL to the external JavaScript file and the variable $localFile you will put the path to your new locally stored file, simple as that!

<?
// script to update local version of Google analytics script

// Remote file to download
$remoteFile = 'http://www.google-analytics.com/ga.js';
$localfile = 'ENTER YOUR ABSOLUTE PATH TO THE FILE HERE';
//For Cpanel it will be /home/USERNAME/public_html/ga.js

// Connection time out
$connTimeout = 10;
$url = parse_url($remoteFile);
$host = $url['host'];
$path = isset($url['path']) ? $url['path'] : '/';

if (isset($url['query'])) {
  $path .= '?' . $url['query'];
}

$port = isset($url['port']) ? $url['port'] : '80';
$fp = @fsockopen($host, '80', $errno, $errstr, $connTimeout );
if(!$fp){
  // On connection failure return the cached file (if it exist)
  if(file_exists($localfile)){
    readfile($localfile);
  }
} else {
  // Send the header information
  $header = "GET $path HTTP/1.0\r\n";
  $header .= "Host: $host\r\n";
  $header .= "User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.6) Gecko/20070725 Firefox/2.0.0.6\r\n";
  $header .= "Accept: */*\r\n";
  $header .= "Accept-Language: en-us,en;q=0.5\r\n";
  $header .= "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7\r\n";
  $header .= "Keep-Alive: 300\r\n";
  $header .= "Connection: keep-alive\r\n";
  $header .= "Referer: http://$host\r\n\r\n";
  fputs($fp, $header);
  $response = '';

  // Get the response from the remote server
  while($line = fread($fp, 4096)){
    $response .= $line;
  }

  // Close the connection
  fclose( $fp );

  // Remove the headers
  $pos = strpos($response, "\r\n\r\n");
  $response = substr($response, $pos + 4);

  // Return the processed response
  echo $response;

  // Save the response to the local file
  if(!file_exists($localfile)){
    // Try to create the file, if doesn't exist
    fopen($localfile, 'w');
  }

  if(is_writable($localfile)) {
    if($fp = fopen($localfile, 'w')){
      fwrite($fp, $response);
      fclose($fp);
    }
  }
}
?>

就是这样,并且应该解决您在使用杠杆浏览器缓存"第三方脚本时遇到的所有问题.

That is it, and should fix any issues you're having with Leverage Browser Caching third party scripts.

来源: http://diywpblog.com/leverage-browser-cache -optimize-google-analytics/

注意:

NOTE:

实际上,这些文件不会对您的实际页面速度产生很大影响.但我可以理解您对Google惩罚您的担心.但这只会在您有 LARGE 个此类外部脚本正在运行的情况下发生.正如我之前所说,与Google相关的任何事情也不会受到您的反对.

In truth, these files don't tend to have a great effect on your actual page speed. But I can understand the worry you have with Google penalising you. But that would only happen if you had a LARGE amount of these external scripts running. Anything Google related will not be held against you either as I stated earlier.

这篇关于利用第三方JS的浏览器缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆