Skip to content

Instantly share code, notes, and snippets.

@ehellman
Last active March 8, 2018 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ehellman/09fa88d17bffc5b19bf811293a735b00 to your computer and use it in GitHub Desktop.
Save ehellman/09fa88d17bffc5b19bf811293a735b00 to your computer and use it in GitHub Desktop.
A way to serve ES6 bundles to ES6 browsers and serve ES5 to the rest.
<!DOCTYPE html>
<html>
<head>
<title>ES6 and Legacy bundle loading</title>
</head>
<body>
Hi
<script>
// populate this on the server or via webpack
window.__APP_CHUNKS__ = {
es: [
'/main.js',
'/first.chunk.js',
'/second.chunk.js'
],
legacy: [
'/main.legacy.js',
'/first.legacy.chunk.js',
'/second.legacy.chunk.js'
]
};
// load correct bundles
var s=document.createElement('script');var c=[];if(s.noModule===false)
{window.__APP_CHUNKS__.es.forEach(function(h){var n=document.createElement('script');
n.setAttribute('src', h);c.push(n);});}else{window.__APP_CHUNKS__.legacy.forEach(
function(b){var g=document.createElement('script');g.setAttribute('src', b);c.push(g);
});};c.forEach(function(v){v.setAttribute('defer',true);document.body.appendChild(v);});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<title>ES6 and Legacy bundle loading</title>
</head>
<body>
<script>
// populate this on the server or via webpack
window.__APP_CHUNKS__ = {
es: [
'/main.js',
'/first.chunk.js',
'/second.chunk.js'
],
legacy: [
'/main.legacy.js',
'/first.legacy.chunk.js',
'/second.legacy.chunk.js'
]
};
var appScript = document.createElement('script');
var chunks = [];
if (appScript.noModule === false) {
// If `noModule` is defined on the script tag, the browser should support Modules
window.__APP_CHUNKS__.es.forEach(function(chunk) {
var es6ChunkScriptTag = document.createElement('script');
es6ChunkScriptTag.setAttribute('src', chunk);
chunks.push(es6ChunkScriptTag);
});
} else {
// Otherwise load the legacy src
window.__APP_CHUNKS__.legacy.forEach(function(chunk) {
var legacyChunkScriptTag = document.createElement('script');
legacyChunkScriptTag.setAttribute('src', chunk);
chunks.push(legacyChunkScriptTag);
});
};
chunks.forEach(function(chunk) {
chunk.setAttribute('defer', true);
document.body.appendChild(chunk);
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment