jrit / web-resource-inliner

Inlines img, script and link tags into the same file
MIT License
66 stars 29 forks source link

`defer` attribute on <script> #70

Open josephrocca opened 3 years ago

josephrocca commented 3 years ago

If the content of script.js is:

alert('this should happen second');

and the content of our HTML file is:

<script src="/script.js"></script>
<script>alert('this should happen first')</script>

Then it gets "compiled" into this:

<script defer>alert('this should happen second');</script>
<script>alert('this should happen first')</script>

But the defer attribute is invalid for inline scripts, so the code doesn't work the same way.

So, maybe, if the defer attribute is present, the script should be converted into a data URL like so:

<script src="data:text/javascript,alert('this should happen second');" defer></script>
<script>alert('this should happen first')</script>

This seems to be a common workaround when defer is wanted for an inline script. The double quotes within the script would need to be escaped, and multi-line attributes are valid (which is useful for readability), so the output could look something like this:

<script src="data:text/javascript,
    alert(&quot;this should happen second&quot;); 
    // more lines of code...
" defer></script>
<script>alert('this should happen first')</script>