利用第三方JS的浏览器缓存

时间:2016-07-14 14:26:35

标签: php apache .htaccess caching google-pagespeed

我在httpd.conf上设置了Expiry

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:

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标头中设置过期日期或最长期限,指示浏览器从本地磁盘而不是通过网络加载以前下载的资源。

如何利用浏览器缓存这个外部JS文件?任何帮助?

3 个答案:

答案 0 :(得分:41)

一个恼人的问题,确实。我担心的不是 轻松 可修复的那个。但你可以做的是使用cron

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

如何执行此操作:

首先,您需要下载正在运行的脚本。我将使用Google Analytics作为示例(这似乎是人们抱怨的最有问题的脚本,但您可以针对任何外部脚本复制此内容)。

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

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

- JS
  - ga.js

接下来,您需要更新调用脚本的页面上的代码,只需更改调用JavaScript文件的目录即可。在我们的案例中,我们将改变这一行:

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';

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

这是CRON发挥作用的地方:

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

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

如果您还为Google Analytics以外的其他外部文件执行此操作,则还需要更改变量$remoteFile。因此,$remoteFile是外部JavaScript文件的URL,变量$localFile是您将路径放到新的本地存储文件中,就这么简单!

<?
// 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);
    }
  }
}
?>

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

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

<强> 注:

事实上,这些文件不会对您的实际页面速度产生很大影响。但是我可以理解你对谷歌惩罚你的担忧。但只有在运行了 LARGE 数量的这些外部脚本时才会发生这种情况。正如我之前所说,任何谷歌相关的内容都不会对你不利。

答案 1 :(得分:3)

不确定此代码段是否会对某人有所帮助,但无论如何这都是我缓存外部js文件的方式。

<script>
 $.ajax({
 type: "GET",
 url: "https://www.google-analytics.com/analytics.js",
 success: function(){},
 dataType: "script",
 cache: true
 });
</script>

答案 2 :(得分:0)

如果您使用的是WordPress,则可以使用“缓存外部脚本”插件。通过最少的插件代码调整,除了Google的文件外,您还可以添加对其他第三方JavaScript文件的支持

相关问题