Skip to content

Instantly share code, notes, and snippets.

@xettri
Created June 16, 2023 17:23
Show Gist options
  • Save xettri/dc103f28b2d0d78c26bfb9efec6ee6f1 to your computer and use it in GitHub Desktop.
Save xettri/dc103f28b2d0d78c26bfb9efec6ee6f1 to your computer and use it in GitHub Desktop.
const webpack = require("webpack");
const { RawSource } = require("webpack-sources");
class DynamicLoadScript {
constructor(options = { filename: "bundle.js" }) {
this.options = options;
}
apply(compiler) {
compiler.hooks.thisCompilation.tap("DynamicLoadScript", (compilation) => {
compilation.hooks.processAssets.tapPromise(
{
name: "DynamicLoadScript",
stage: webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_TRANSFER,
},
() =>
new Promise((resolve) => {
try {
const assetNames = Object.keys(compilation.assets)
.filter((v) => v.endsWith(".js"))
.filter((v) => {
const chunk = compilation.chunks.find((chunk) =>
chunk.files.includes(v)
);
return chunk && chunk.isOnlyInitial();
})
.map((v) => compilation.options.output.publicPath + v);
const code = `
(function (f) {
for(let i = 0; i < f.length; i++) {
let s = document.createElement("script");
s.src = f[i];
s.defer = true;
document.head.appendChild(s);
}
})(${JSON.stringify(assetNames)});
`;
compilation.assets[this.options.filename] = new RawSource(code);
} catch (err) {}
resolve();
})
);
});
}
}
module.exports = DynamicLoadScript;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment