【问题标题】:Leverage browser caching for 3rd party JS为 3rd 方 JS 使用浏览器缓存
【发布时间】:2016-11-17 12:40:50
【问题描述】:

我在我的 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:

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 文件?有什么帮助吗?

【问题讨论】:

    标签: php apache .htaccess caching google-pagespeed


    【解决方案1】:

    确实是一个烦人的问题。恐怕不是一个容易可以修复的。但是你可以做的是使用cron

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

    怎么做:

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

    查看您的代码并找到脚本的名称,在我们的例子中是:google-analytics.com/ga.js。将此 URL 弹出到您的网络浏览器中,它将显示源代码。只需复制一份并保存为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 数量的这些外部脚本时才会发生。正如我之前所说,任何与 Google 相关的事情都不会对您不利。

    【讨论】:

    • 这不能用所有 3rd 方脚本来完成。其中许多将需要从其原始域访问,以启用 cookie 设置和其他特定于域的行为。
    • 另一种保留 cookie 和其他域特定行为的解决方案是通过您的服务器代理这些请求,但指示代理添加到期日期(并且不要忘记确保代理只接受您期望的 URL)。我以前见过一个 WordPress 插件这样做。
    • 这是否需要编辑每个加载外部脚本的插件?
    【解决方案2】:

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

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

    【讨论】:

    • 我测试了这个方法但是脚本没有缓存。
    • 您可能需要将脚本包装到 jQuery 函数中,否则您的 WordPress 构建将显示错误
    【解决方案3】:

    如果您使用 WordPress,则可以为此使用“缓存外部脚本”插件。通过最少的插件代码调整,您可以添加对除 Google 文件之外的其他 3rd 方 javascript 文件的支持

    【讨论】:

    • 值得一提的是,这个插件需要php知识以及阅读和理解你在看什么的能力。如果你不是 PHP 程序员,你将无法使用这个插件。
    猜你喜欢
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    • 1970-01-01
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    相关资源
    最近更新 更多