问题原文
原帖链接 · Ahmed · CC BY-SA 3.0
When a web page contains a single CSS file and an image, why do browsers and servers waste time with this traditional time-consuming route:
- browser sends an initial GET request for the webpage and waits for server response.
- browser sends another GET request for the css file and waits for server response.
- browser sends another GET request for the image file and waits for server response.
When instead they could use this short, direct, time-saving route?
- Browser sends a GET request for a web page.
- The web server responds with (index.html followed by style.css and image.jpg)
已采纳解答
原帖链接 · Stephen Ostermiller · CC BY-SA 4.0
The short answer is "Because HTTP wasn't designed for it".
Tim Berners-Lee did not design an efficient and extensible network protocol. His one design goal was simplicity. (The professor of my networking class in college said that he should have left the job to the professionals.) The problem that you outline is just one of the many problems with the HTTP protocol. In its original form:
- There was no protocol version, just a request for a resource
- There were no headers
- Each request required a new TCP connection
- There was no compression
The protocol was later revised to address many of these problems:
- The requests were versioned, now requests look like
GET /foo.html HTTP/1.1 - Headers were added for meta information with both the request and response
- Connections were allowed to be reused with
Connection: keep-alive - Chunked responses were introduced to allow connections to be reused even when the document size is not known ahead of time.
- Gzip compression was added
At this point HTTP has been taken about as far as possible without breaking backwards compatibility.
You are not the first person to suggest that a page and all its resources should be pushed to the client. In fact, Google designed a protocol that can do so called SPDY.
Today both Chrome and Firefox can use SPDY instead of HTTP to servers that support it. From the SPDY website, its main features compared to HTTP are:
- SPDY allows client and server to compress request and response headers, which cuts down on bandwidth usage when the similar headers (e.g. cookies) are sent over and over for multiple requests.
- SPDY allows multiple, simultaneously multiplexed requests over a single connection, saving on round trips between client and server, and preventing low-priority resources from blocking higher-priority requests.
- SPDY allows the server to actively push resources to the client that it knows the client will need (e.g. JavaScript and CSS files) without waiting for the client to request them, allowing the server to make efficient use of unutilized bandwidth.
If you want to serve your website with SPDY to browsers that support it, you can do so. For example Apache has mod_spdy.
SPDY has become the basis for HTTP version 2 with server push technology.
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
