php 为 3rd 方 JS 利用浏览器缓存
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38376871/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Leverage browser caching for 3rd party JS
提问by Vivek Tankaria
I have set Expiry on my httpd.conf
我已经在我的 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"
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:
这有助于浏览器缓存图像、字体文件、站点自己的 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 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.
Google Pagespeed Insights 对上层文件说: 在静态资源的 HTTP 标头中设置到期日期或最长期限会指示浏览器从本地磁盘而不是通过网络加载先前下载的资源。
How to leverage browser cache this external JS files ? Any Help ?
如何利用浏览器缓存这个外部 JS 文件?任何帮助?
回答by Joe
An annoying issue, Indeed. Not one that is as easilyfixable I'm afraid. But what you can do is use a cron
.
一个烦人的问题,确实。恐怕没有那么容易修复的。但是您可以做的是使用cron
.
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.
首先,请记住,谷歌不太可能因为他们自己的工具(比如分析)而惩罚你。但是,如前所述,它可以使用 a 修复cron
,这基本上意味着您在本地加载 JavaScript 并拉取更新的脚本。
How to do this:
这该怎么做:
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 作为示例(这似乎是人们抱怨的最有问题的脚本,但您可以将其复制到任何外部脚本中)。
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
.
查看您的代码并找到脚本的名称,在我们的示例中为:google-analytics.com/ga.js
. 将此 URL 弹出到您的 Web 浏览器中,它将显示源代码。只需复制一份并将其另存为ga.js
.
Save this newly created JavaScript file onto your webserver, in my case:
将这个新创建的 JavaScript 文件保存到您的网络服务器上,在我的情况下:
- JS
- ga.js
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:
接下来,您需要更新调用脚本的页面上的代码,只需更改调用 JavaScript 文件的目录即可。再一次在我们的例子中,我们将改变这一行:
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
to
到
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.
此时,您的网站现在将从您的网站本地运行脚本!但是,这意味着脚本永远不会更新。除非你每周都重新运行这个简短的过程。这取决于你......但我太懒了。
This is where the CRON comes into play:
这就是 CRON 发挥作用的地方:
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
工作的选项。在 Hostinger 上,它位于您的托管面板上,在 GoDaddy 上,您可以在“内容”选项下找到它。
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.
将以下脚本放入您cron
的$localfile
. 此脚本的作用是从 Google 为ga.js
文件提取更新的脚本。您可以根据您希望它运行此过程的频率设置时间范围。从每小时一次到每月一次,甚至更久。
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!
如果您还对 Google Analytics 以外的外部文件执行此操作,则您还需要更改变量$remoteFile
. 所以,$remoteFile
是的URL外部JavaScript文件和变量$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);
}
}
}
?>
That is it, and should fix any issues you're having with Leverage Browser Caching third party scripts.
就是这样,应该可以解决您在使用 Leverage Browser Caching 第三方脚本时遇到的任何问题。
Source: http://diywpblog.com/leverage-browser-cache-optimize-google-analytics/
来源:http: //diywpblog.com/leverage-browser-cache-optimize-google-analytics/
NOTE:
笔记:
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 LARGEamount of these external scripts running. Anything Google related will not be held against you either as I stated earlier.
事实上,这些文件往往不会对您的实际页面速度产生很大影响。但我能理解你对谷歌惩罚你的担忧。但是,如果你有一个,只会出现大运行这些外部脚本量。正如我之前所说的那样,任何与 Google 相关的事情都不会对您不利。
回答by Nuno Sarmento
Not sure if this code snippet will help someone, but anyway this is how I cache an external js file.
不确定此代码片段是否会对某人有所帮助,但无论如何这就是我缓存外部 js 文件的方式。
<script>
$.ajax({
type: "GET",
url: "https://www.google-analytics.com/analytics.js",
success: function(){},
dataType: "script",
cache: true
});
</script>
回答by Ron Warshawsky
If you are on WordPress, you can use "Cache External Scripts" plugin for this. With minimal plugin code tweaking, you can add support for the other 3rd party javascript files in addition to the Google ones
如果您使用 WordPress,您可以为此使用“缓存外部脚本”插件。通过最少的插件代码调整,除了 Google 文件之外,您还可以添加对其他 3rd 方 javascript 文件的支持