[wp-trac] [WordPress Trac] #41086: Conditional loading of CSS files from (for example) shortcodes

WordPress Trac noreply at wordpress.org
Fri Jun 16 19:51:48 UTC 2017


#41086: Conditional loading of CSS files from (for example) shortcodes
-----------------------------+-----------------------------
 Reporter:  theMikeD         |      Owner:
     Type:  feature request  |     Status:  new
 Priority:  normal           |  Milestone:  Awaiting Review
Component:  Shortcodes       |    Version:  4.8
 Severity:  normal           |   Keywords:
  Focuses:                   |
-----------------------------+-----------------------------
 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.

--
Ticket URL: <https://core.trac.wordpress.org/ticket/41086>
WordPress Trac <https://core.trac.wordpress.org/>
WordPress publishing platform


More information about the wp-trac mailing list