Reputation: 6236
Is there anyway to preserve execution order of scripts that are a mix of either 'deferred' or inline ?
For eg. consider the following scenario -
<head>
<script src="/polyfills.js" />
<script>
// Small inline script that needs polyfills to work
</script>
<script src="/feature1.js" defer>
<script src="/feature2.js" defer>
</head>
My goal is to make all the scripts have defer
behaviour and maintain execution order. However, here, I cannot add defer
to the polyfills script as doing so will break the inline script.
polyfills (defer) => inline-script (how?) => feature1 => feature2
The inline script is a tiny code fragment, and not worth wasting a request over.
Could I for example write a function that would wrap the inline script and execute if only after polyfills have loaded)?
Upvotes: 5
Views: 3784
Reputation: 1442
According to this answer it's technically possible, as long as you're willing to base64-encode your script and set it as a data source. This will be a nightmare to debug if something goes wrong, but might be your only shot if you have a small inline fragment that must be included in the proper deferred order.
Upvotes: 0
Reputation: 597
As defer attribute works only with external scripts tag with src. Here is what you can do mimic defer for inline scripts. Use DOMContentLoaded event.
<script src="/polyfills.js" defer></script>
<script src="/feature1.js" defer></script>
<script src="/feature2.js" defer></script>
<script>
document.addEventListener("DOMContentLoaded", function() {
// Your inline scripts which uses methods from polyfills.js.
});
</script>
This is because, DOMContentLoaded event fires after defer attributed scripts are completely loaded. You might not have to wait for 'load' event.
This is the closest you could do.
Upvotes: 3
Reputation: 19288
If you want it to retain the order of a sandwiched inline script, then, with regard to deferring, I think you are stuffed.
If all three src'd scripts are deferred, then there's no naturally-occurring intermediate event (after the polyfills but before the features) on which to trigger a handler - which is what you want.
For the record, here's how to delay an inline script until all deferred scripts have loaded, which will possibly offer some benefit but no as much as you were hoping for.
<head>
<script src="/polyfills.js" defer></script>
<script src="/feature1.js" defer></script>
<script src="/feature2.js" defer></script>
<script>
window.addEventListener('load', function() {
// Small inline script that needs polyfills to work
});
</script>
</head>
Upvotes: 3