问题
Can I use JavaScript to detect if the user's browser supports gzipped content (client side, not node.js or similar)?
I am trying to support the following edge case:
There are a lot of possible files that can load on a particular web app and it would be better to load them on demand as necessary as the application runs rather than load them all initially. I want to serve these files off of S3 with a far-future cache expiration date. Since S3 does not support gzipping files to clients that support it, I want to host two versions of each file -- one normal, and one gzipped with content-type
set to application/gzip
. The browser of course needs to know which files to request. If JavaScript is able to detect if the browser supports gzipped content, then the browser will be able to request the correct files.
Is this possible?
回答1:
Javascript can't, but you can use Javascript to detect wether or not the browser supports gzipped content.
I commented above and would just like to reiterrate, you should use CloudFront anyway, which does gzip content. If you are using S3, then there is zero reason why you would not want to use CloudFront, however, for the purposes of answering your question...
This blog post perfectly addresses how you would detect if the browser supports Gzip.
http://blog.kenweiner.com/2009/08/serving-gzipped-javascript-files-from.html
Here is a quick summary:
1) Create a small gzipped file, gzipcheck.js.jgz, and make it available in CloudFront. This file should contain one line of code:
gzipEnabled = true;
2) Use the following code to attempt to load and run this file. You'll probably want to put it in the HTML HEAD section before any other Javascript code.
<script type="text/javascript" src="gzipcheck.js.jgz"> </script>
If the file loads, it sets a flag, gzipEnabled, that indicates whether or not the browser supports gzip.
回答2:
Well cloudfront does not gzip content automatically. Till the time Amazon decides to do automatic gzip compression in S3 and Cloudfront one has to use the below workaround.
- In addition to the normal version, create a gzipped version of the file and upload on S3. If the file name is style.css the gzipped version should be named style.css.gz.
- Add a header to the file with key=Content-Encoding & value=gzip to the file. This is needed so that browsers understand that the content is encoded using gzip. The header can be added using S3 api or the popular S3 file manager tools like Cloudberry, Bucket Explorer, etc
- Also add the correct Content-Type header for the file. e.g for style.css it should be Content-Type: text/css.
- In the webpage include the file normally
- Use the above mentioned javascript to detect if the browser supports gzip encoding. If found true replace the file name e.g style.css with style.css.gz
来源:https://stackoverflow.com/questions/7153220/can-javascript-detect-if-the-users-browser-supports-gzip