【问题标题】:Cache busting with nanoc使用 nanoc 进行缓存破坏
【发布时间】:2013-01-24 19:03:14
【问题描述】:

如何使用 Nanoc 实现缓存清除?

例如,将 MD5 校验和添加到 HTML 和 CSS 文件上的所有 image/font/js/etc 资源链接。例如,如果我有index.htmlimages/badger.jpg,我希望将页面上的图片链接更改为类似

`href="images/badger.jpg?12345"`

假设 12345 是 badger.jpg 的正确 MD5 哈希。

【问题讨论】:

    标签: nanoc


    【解决方案1】:

    您可以采用路由方法。我建议使用实际不同的文件名而不是查询字符串 - 一些 http 缓存不会缓存带有查询字符串的 url。

    route '/stylesheet/' do
      csum = [File.open(item[:filename]).read.checksum]
      # add other files you include from your stylesheet.less (if you use less)
      csum += Dir['content/styles/*'].select { |i| File.file?(i) }.map { |f| File.read(f).checksum }
      '/style-' + csum.checksum + '.css'
    end
    
    route '*' do
      ext = item[:extension]
      versionexts = ['css','js']
    
      if versionexts.include?(ext)
        # versioned filenames, depending on the checksum of the source file
        # these files shouldn't depend on other sources, or you have to checksum them too (see above)
        item.identifier.chop + '-' + File.read(item[:filename]).checksum + '.' + ext
      elsif item.binary?
        # Write item with identifier /foo/ to /foo.ext
        item.identifier.chop + '.' + ext
      else
        # Write item with identifier /foo/ to /foo/index.html
        item.identifier + 'index.html'
      end
    end
    

    您不能在路由中使用生成内容的校验和,因为路由是在编译之前完成的。

    【讨论】:

    • 现在,如果我在 html、css 文件中引用了我的版本化 css、js、png 文件,nanoc 会理解它并更新引用以匹配这些路由吗?那太棒了。
    【解决方案2】:

    Arjan van der Gaag 专门为此制作了一颗宝石:https://github.com/avdgaag/nanoc-cachebuster

    To quote the man himself:

    使用简单,只需要安装gem即可:

    $ gem install nanoc-cachebuster 
    

    需要 gem 并包含 帮手开始:

    # in default.rb
    require 'nanoc3/cachebuster' 
    include Nanoc3::Helpers::CacheBusting 
    

    您现在可以使用#fingerprint 方法 在您的路由规则中:

    route '/assets/styles/' do
      item.identifier.chop + fingerprint(item) + '.' + item[:identifier]
    end
    

    gem 将确保在您编译您的文件时更新对您指纹文件的引用 网站。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-29
      相关资源
      最近更新 更多