0

How can I enqueue a CSS code only on the pages which use that CSS?

Usually it's quite easy to know if a particular CSS or JS is used on a WordPress Post: it's enough to check if the shortcode is used in that post.

Is there any WP functionality to support the developer in this task?

10
  • 1
    Yes, you can wp_enqueue_script() asset in your shortcode method/function. So only when shortcode is used, asset loads.
    – sandrodz
    Commented Nov 7, 2018 at 19:23
  • 1
    @sandrodz it's not so easy, because you have to enqueue script/style before it is printed (styles should be printed in header, and shortcodes are processed after header is printed). Commented Nov 7, 2018 at 20:41
  • 1
    @Revious You can achieve that, but it doesn't make much sense. CSS/JS files should be cached by browsers. Also, they should get combined and minified, so loading different set of JS/CSS files on different pages is rather harmful for performance. Commented Nov 7, 2018 at 20:42
  • 1
    @Revious still, combine and minify - it will save lot more bandwidth and requests than loading different set of files... Commented Nov 7, 2018 at 20:50
  • 1
    @KrzysiekDróżdż Did I say it was easy? yes you first register assets, then enqueue.
    – sandrodz
    Commented Nov 7, 2018 at 22:15

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.