11ty / eleventy-plugin-bundle

Little bundles of code, little bundles of joy.
72 stars 3 forks source link

Conditional <script> tags #8

Closed adamwolf closed 2 months ago

adamwolf commented 1 year ago

I'm loving this plugin!

I was working on a little site where some pages had some non-essential Javascript that I put at the end of the body. I set up a noncritical bundle, and it worked pretty well, until I tried to make the whole script tag conditional on the noncritical bundle being empty.

At first, I was pretty confused because nunjucks was saying that the contents of the bundle were both the empty string and also 40-some characters long, but of course this ended up being the out-of-order render stuff. I tried to dig in a bit more and get the conditional tags, but I didn't understand the out-of-order render stuff enough to get it to work.

I ended up adding a "hasNoncriticalJS" boolean on the whole page and including the <script> tag and contents based on that boolean.

It works fine--but now I'm really curious. :)

Is this already supported? If it isn't, is there anywhere where it'd make sense to add something like this? A way to put a prefix-suffix around a bundle if the bundle isn't empty, maybe?

zachleat commented 1 year ago

It isn’t supported yet! I would like to have this though!

I’ve been thinking on it—I’m curious how to maintain full control over the parent HTML without it being too esoteric (a la the prefix/suffix idea)

adamwolf commented 1 year ago

The syntax might be the hardest part! :)

noelforte commented 10 months ago

A workaround that just came to me today that I've implemented and it works great is to add an HTML transform that looks for empty <style>, <script> and <link> tags resulting from empty bundles and does a string replace to eliminate them from the output. Not a perfect solution but it gets the job done. Details are here: https://github.com/11ty/eleventy-plugin-webc/issues/82#issuecomment-1912897259

zachleat commented 2 months ago

Shipping with Bundle Plugin v3.0.0 as part of Core v3.0.0-alpha.21 and v3.0.0-beta.2

(no additional configuration needed)