WordPress.org

Make WordPress Core

Opened 2 years ago

Last modified 2 years ago

#41086 new feature request

Conditional loading of CSS files from (for example) shortcodes

Reported by: theMikeD Owned by:
Milestone: Awaiting Review Priority: normal
Severity: normal Version: 4.8
Component: Shortcodes Keywords:
Focuses: Cc:
PR Number:

Description

The nature of HTTP/2 is such that loading several smaller CSS files instead of one monolithic CSS file is best practice now. Great!

However. I have found several cases where loading css files as required via wp_enqueue_style() doesn't work because I won't know what CSS file I need until I start rendering the page, which is well past when that function is called.

For example, with shortcodes. I have a plugin installed and active that provides a [shortcode]. But this [shortcode] is not used on every page; or even most pages (such as a goldilock pricing table). So: how do I prevent the CSS for that shortcode from being loaded when [shortcode] is not used? Or from the other direction: how do you load the CSS for [shortcode] only when that shortcode is used, and only once if the shortcode is used multiple times?

If I understand wp_enqueue_styles() correctly, anything enqueued after that action is run is sent to print_late_styles() but those go into the footer, leading to jank.

The only solution I have found is to write the HTML to load the css file directly into the output stream. To that end I wrote this to avoid dupes:

https://gist.github.com/th…/f002f696f365aff7c8252f6365cc7d5e

It works but it feels hacky. To my way of thinking a better solution would be either a mod to wp_enqueue_style() or a new function that allows for the enqueueing of styles but their output on demand, and once per page, similar to what I wrote above.

If the answer is just, "don't do that," (which is what I've heard at least once while trying to find a solution) so be it. But the shortcode in question is loading 63k of CSS on every page and, caching be damned, I don't want it to.

Change History (1)

#1 @theMikeD
2 years ago

Mod: please edit the original post and replace link to gist with this one; I can't edit my own ticket it seems.

https://gist.github.com/theMikeD/f002f696f365aff7c8252f6365cc7d5e

Note: See TracTickets for help on using tickets.