Since HTTP/2 was launched in 2013, HTTP/2 has made great progress. Browser platforms basically provide HTTP/2 support, and some large domestic platforms such as Zhihu and Douban have also switched to HTTP/2.

HTTP / 2

Multiplexing requests prioritizes requests to compress the HTTP header push stream

HTTP/2 support:

Chrome, Firefox, Internet Explorer 11(Windows 10) are all supported

Details can be found at caniuse.com/#search=htt…

HTTP/2 caching:

HTTP/2 can’t be cached, as we found on the web. It just needs to be configured on the server side, such as :” EXPIRES “:”Tue, 09 Oct 2018 11:27:20 GMT.”

Test method:

ResponseType = ‘blob’; xhr.responseType = ‘blob’; xhr.responseType = ‘blob’; xhr.responseType = ‘blob’; Because ajax requests to come is a binary string, so to parse, back-end read a file and returns the file content to set up the same parameters for binary), the result of the request by img. SRC = window. URL. CreateObjectURL (data); Parse to image urls.

According to the two loading methods, I constructed four groups of test codes and selected two groups of images with the size of 237KB and 2KB respectively for testing:

  1. HTTP / 2 && AJAX to load
  2. HTTP/2&& browser loading
  3. Http1.1 && AJAX to load
  4. Http1.1&& browser loading

Other Matters needing attention

When using a browser, ensure that the HTTPS protocol is used for access

Chrome allows local HTTPS, go to Chrome ://flags/#allow-insecure-localhost and set its value to enabled

In Chrome, right-click on the header of the Network column to open the Protocol column to see if the requested protocol is H2

The favicon.ico file is automatically loaded on the first load, which may cause errors

Code implementation

localhost-cert.pem

-----BEGIN CERTIFICATE-----
MIIC+zCCAeOgAwIBAgIJALUOjGkvsHSZMA0GCSqGSIb3DQEBCwUAMBQxEjAQBgNV
BAMMCWxvY2FsaG9zdDAeFw0xODAxMjUwNTMxMDFaFw0xODAyMjQwNTMxMDFaMBQx
EjAQBgNVBAMMCWxvY2FsaG9zdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC
ggEBANRicexesNtTbjVnxKyEWalFovZUEYQ/FRjArJAndaEBSVlsrTRFrp3nEUNx
6O6EUM4SrfOTCfEW6Pi9YqH8wVk8/G3BCOG99as6GIHabkbC79UiNdDhAQLr10+g
gaXl+QYxvGEvk/Qb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Z4dyYvTQhIh5cUxlJX4U4HMDOXNnnQQuSjbBrJ
Ku4lmZ9qd5iwmNnennj5Bph2ATvUApSxnx5qnWvhAoGAPKLPKCuVoJS6FUZXl4ef
Pm0JYq+vl301wFAs9+4sf9kB3gA+xRFt8XHOmhaCgTDTea/EvSCR4FDO1BZgKpre
iyeQ5YdPYJ7sVq0TgQLCMzyqopG2f2/mmnJ/jzZhOp2C+gtqO0sKko6MZZTBEs3G
M94dSazKORHbqv9K6v49nls=
-----END PRIVATE KEY-----

Copy the code

index.js

const http2 = require('http2');
const fs = require('fs');

const server = http2.createSecureServer({
  key: fs.readFileSync('localhost-privkey.pem'),
  cert: fs.readFileSync('localhost-cert.pem')}); server.on('error', (err) => console.error(err));
server.on('socketError', (err) => console.error(err));

server.on('request', (request, response) => {
    console.log('./images'+request.url); // The format must be binary or an error will occur'./images'+request.url
    var content =  fs.readFileSync('./images'+request.url,"binary");   
    response.writeHead(200, {
        "Content-Type": "image/png"."expires":"Tue, 09 Oct 2018 11:27:20 GMT"."Access-Control-Allow-Origin": "http://localhost:8080"
    });
    response.write(content,"binary"); Response.end (); }); server.listen(8443);Copy the code

index.html

<! DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>HTTP/2 test </title> <script SRC ="./http.js"></script>
    </head>
    <body>
123
<div id="imgContainer"></div>
    </body>
    <script>
        for(var i=1; i<16; i++){
            // GET('https://localhost:8443/'+i+'.png'.function(response){
            //     drawImg(response);
            // });

            // GET('http://localhost:8080/http2test/images/'+i+'.png'.function(response){
            //     drawImg(response);
            // });

            // var myImage = new Image();
            // myImage.src = 'https://localhost:8443/'+i+'.png';
            // document.body.appendChild(myImage);

            var myImage = new Image();
            myImage.src = 'http://localhost:8080/http2test/images/'+i+'.png';
            document.body.appendChild(myImage);

            
        }


        function drawImg(data){
            var img = new Image();
            img.src = window.URL.createObjectURL(data);
            img.onload = function(){
                window.URL.revokeObjectURL(img.src);
            }
            document.body.appendChild(img);
        }
        
    </script>
</html>
Copy the code

http.js

/** * the library that initiates the asynchronous request */function GET(url,callback){
    var xhr = new XMLHttpRequest();
    xhr.open('GET',url,true);
    xhr.responseType = 'blob';
    xhr.onload = function() {if(xhr.readyState === 4 && xhr.status >= 200 && xhr.status <300 && xhr.response){
            callback(xhr.response);
        }
    }
    xhr.send();
 }
Copy the code

Rename. Js (for quickly generating a large number of identical files with different names)

const fs = require('fs');


var path = './images';
var dirs = fs.readdirSync(path);
var n = 0;
for(let i in dirs){
    var filename = dirs[i].split('. ');
    var type = filename[filename.length-1];
    if(type= ='png'){
        fs.renameSync(path+'/'+dirs[i],path+'/'+n+'.png');
        n +=1;
    }else{
        fs.unlinkSync(path+'/'+dirs[i]);
    }
    console.log('Processing done:'+dirs[i]);
}
Copy the code

Full code address: running HTTP /2 versus HTTP /1.1 tests

Test results:

Because local loading is too fast, the following tests used Chrome’s fast3G mode to simulate production network conditions as much as possible.

type Request way Large (237KB) small (2KB) file The file number Loading time
HTTP/2 Browser loading small 40 2.81 s
HTTP / 1.1 Browser loading small 40 5.89 s
HTTP/2 AJAX small 40 2.49 s
HTTP / 1.1 AJAX small 40 5.82 s
HTTP/2 Browser loading big 40 52.59 s
HTTP / 1.1 Browser loading big 40 52.57 s
HTTP/2 AJAX big 40 52.66 s
HTTP / 1.1 AJAX big 40 52.58 s

It can be seen that the advantage of _HTTP/2 is mainly reflected in the loading of a large number of small images, but it does not have a great advantage for the loading of a small number of large images. Moreover, if the network conditions are very good, HTTP/2 can not reflect the advantage because of the very fast loading.

HTTP/2 in WebGIS and other map applications:

WebGIS was popularized by tile technology, which is requests and files, and each tile loaded requires a request for images or other files in the server. Most map tiles are about 40KB PNG files, and the number of maps loaded at a time is about 20. Due to the limitations of HTTP1.1 itself, the browser can load only six files at once (slightly different browser policies), and when the map viewer window moves, the front end sends a large number of Simultaneous AJAX requests to load the tile. At this point, the browser blocks and waits for the files in front of the queue to finish loading before loading the files behind it.

The concurrency feature of HTTP/2 solves this problem and fits this scenario.

Amap uses HTTP/2 in part, Google Maps uses HTTP/2 in whole, Baidu Map does not use HTTP/2 yet, Mapbox does not use HTTP/2

The only problem is that you need to figure out the market occupancy of IE11. If the occupancy is still too high, it’s a hassle to deal with after switching.

Reference:

Use of HTTP/2 in Node.js: nodejs.org/api/http2.h…

HTTP/2 in PHP: www.phpchina.com/article-402…