How to force server to send all imported ES6 modules in one http request

Viewed 214

Please take a look at the following code;

import * as test from "./test2.js"

function test1()
{
}

let a=1
console.log(test.b)
test.test1();
console.log( "Finished" );
<html>
<head>
    <script type="module" src="./test.js"></script>
</head>
<body>
<p>Hello World!</p>
</body>
</html>

As you can see above, I import another JS file inside my module. But in this case I have two http requests in the network; one for "test.js" and one for "test2.js".

Can I send both files in one http request? I don't want to concatanate JS file. I am looking for a solution realted ES6 modules; something like "preload" keyword and please don't suggest external libraries to do it

3 Answers

Can I send both files in one http request?

Not trivially.

You'd need the response to the request for test.js to be a single JS file that includes both the content of your existing test.js and test2.js.

You need to create that file somehow. It certainly isn't a feature of standard HTTP servers.

You've rejected the use of external libraries, but the usual way to do this would be to use a tool like Webpack to combine the modules into a single (non-module) JS script.

If you were using HTTP/2 then you could use multiplexing.

umm your http client would have to be smart enough to do that or your http server would have to signal to the http client that it parsed the js file and it knows that it also needs the others...

You can achieve this with a custom HTTP server but as for IIS or apache I am not sure that is easily possible without another piece of software / plugin to do the file reading and hinting.

I suggest you look into enabling http/2 on your server so that you can reuse http connections as well as gain other performance benefits. The protocol is already supported by all major browsers and will be used automatically as long as the server supports it. Check out this medium article on the basics, especially for your case

  • Request multiplexing over a single TCP connection
  • Request pipelining
Related