How to force the browser to reload cached CSS/JS files?

后端 未结 30 4360
青春惊慌失措
青春惊慌失措 2020-11-21 05:49

I have noticed that some browsers (in particular, Firefox and Opera) are very zealous in using cached copies of .css and .js files, even be

30条回答
  •  失恋的感觉
    2020-11-21 06:07

    I recently solved this using Python. Here the code (should be easy to adopt to other languages):

    def import_tag(pattern, name, **kw):
        if name[0] == "/":
            name = name[1:]
        # Additional HTML attributes
        attrs = ' '.join(['%s="%s"' % item for item in kw.items()])
        try:
            # Get the files modification time
            mtime = os.stat(os.path.join('/documentroot', name)).st_mtime
            include = "%s?%d" % (name, mtime)
            # this is the same as sprintf(pattern, attrs, include) in other
            # languages
            return pattern % (attrs, include)
        except:
            # In case of error return the include without the added query
            # parameter.
            return pattern % (attrs, name)
    
    def script(name, **kw):
        return import_tag("""""", name, **kw)
    
    def stylesheet(name, **kw):
        return import_tag('', name, **kw) 
    

    This code basically appends the files time-stamp as a query parameter to the URL. The call of the following function

    script("/main.css")
    

    will result in

    
    

    The advantage of course is that you do never have to change your html again, touching the CSS file will automatically trigger a cache invalidation. Works very good and the overhead is not noticeable.

提交回复
热议问题