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

查看:34
本文介绍了为 3rd 方 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 不太可能因为他们自己的工具(例如分析)而惩罚您.但是,如前所述,它可以使用 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.

如何做到这一点:

首先,您需要下载正在运行的脚本.我将使用 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 发挥作用的地方:

几乎每一个托管服务都有一个选项供您设置 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/

注意:

事实上,这些文件往往不会对您的实际页面速度产生很大影响.但我能理解你对谷歌惩罚你的担忧.但是,只有当您运行 大量 数量的这些外部脚本时,才会发生这种情况.正如我之前所说,任何与 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.

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

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