Skip to content

Instantly share code, notes, and snippets.

@Rich-Harris
Created April 2, 2017 15:26
Show Gist options
  • Save Rich-Harris/99f63af4c25d8919f4a1988fb5f9f4d9 to your computer and use it in GitHub Desktop.
Save Rich-Harris/99f63af4c25d8919f4a1988fb5f9f4d9 to your computer and use it in GitHub Desktop.
Server-push for ES2015 modules on unpkg.com

Following this convo:

Your browser requests https://unpkg.com/foo:

<script type='module' src='https://unpkg.com/foo'></script>

unpkg responds with the contents of foo...

import bar from './bar.js';
alert( bar );

...but it also scans the file and sees the import declaration, resolves it (because it already knows that /foo resolves to /foo@1.2.3/lib/index.js) and is thus able to server push https://unpkg.com/foo@1.2.3/lib/bar.js.

The browser receives foo.js, and parses it. Upon doing so, it sees that it needs to fetch bar.js before it can evaluate the code, so it makes a separate request to https://unpkg.com/foo@1.2.3/lib/bar.js. But because unpkg had already pushed bar.js, the file is already on its way (may even have already arrived, in fact), saving the costs of going back and forth to progressively fetch new modules.

If this worked out-of-the-box, unpkg's speed would be pretty hard to beat.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment