简体   繁体   中英

How to invalidate cache for JS file loaded from bookmarklet?

I have a bookmarklet that looks like this:

javascript:(function(){var a=document.createElement("script");a.type="text/javascript";a.src="//example.com/script.min.js";a.charset="utf-8";document.body.appendChild(a)})();

I have the following in my .htaccess file to allow files to be cached:

<IfModule mod_expires.c>
    # Enable expirations
    ExpiresActive On
    # Default directive
    ExpiresDefault "access plus 1 month"
    # My favicon
    ExpiresByType image/x-icon "access plus 1 year"
    # Images
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    # CSS
    ExpiresByType text/css "access 1 month"
    # Javascript
    ExpiresByType application/javascript "access plus 1 month"
</IfModule>

The problem is that sometimes I make changes to script.js and I want people using the bookmarklet to get the updated file to prevent problems.

For files loaded on my website, I overcome this issue by versioning the files, but I don't see how I could do that with the bookmarklet.

Clearly there is no way for the client to magically know that you have updated the script unless it checks the server.

So with that fact established you simply must decide how to balance the cost of checking your server vs what amount of delay is acceptable, and consider that together with the amount of effort you wish to put into solving the problem.

The easiest solution IMHO is to simply change the cache time to a day or two.

Also, look up "http etag". If done right, the client will check the server each time, but the amount of data being transmitted should be trivial.

If you don't want to change your mod_expires rules universally for all ".js" files, there is nothing in the world that says you have to use ".js" as the extension for all script files. The client doesn't care.

Another solution is to append a date string like "?dt=2014-07-31-01:00:32" to the script file, but you can craft the date string to force a fresh download once per day, or every couple of days, or once per week, or month, or whatever.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM