I know most browsers support http/2 for loading the pages but does this mean I can leverage it when I make api calls using XmlHttpRequest ?
More specifically my question is if I make 2 calls to fetch data using XmlHttpRequest does it ensure that both of them use the same tcp connection underneath ? None of the documentation I read any where specifies any thing about http2 support for XmlHttpRequest or how I can explicitly open a http2 connection, make some calls leveraging this and then close the connection.
The okHttp, jetty and other libraries in java offer client libraries to support this. But the javascript support is not clear.
When the browser and server both support HTTP/2 then it will be used for all calls from the browser - including XHR. You don't need to do anything special in your javascript to enable this. That's one of the great things about the way HTTP/2 was implemented.
If you are asking how to ensure the connection is held open for as you want to reuse the connection then the http/2 spec says:
HTTP/2 connections are persistent. For best performance, it is
expected that clients will not close connections until it is
determined that no further communication with a server is necessary
(for example, when a user navigates away from a particular web page)
or until the server closes the connection.
...
Servers are encouraged to maintain open connections for as long as
possible but are permitted to terminate idle connections if necessary.