Share

Updated: January 15th, 2010

24 Responses to “[Wordpress Plugin Development] How To Include CSS and JavaScript Conditionally And Only When Needed By The Posts”

    13 Comments:
  1. Hi Artem, Great article! This topic is very important and should be addressed by everyone extending WordPress. One thing that I noticed was that – In the function relating to shortcodes – was that this line:

    if (stripos($post->post_content, '[code]'))

    is restrictive in that it will only match when the shortcode has no attributes. I have outlined the following solution which matches a unique html comment instead:

    http://mfields.org/2009/12/13/how-to-create-a-wordpress-plugin-that-only-prints-css-for-certain-posts-pages-or-attachments/

    • Michael, thanks for chiming in.

      I deliberately included a simple example that only matched [code] as I also wanted to avoid using regex, for speed purposes.

      Obviously, the plugin developer will want to use their own pattern matching and this is where my warning comes into play. I'd rather see them match on "[code" instead and potentially overinclude than miss one and not include.

      I looked at the functions in the shortcode API and what I was looking for is an easy way to see if a shortcode is present in a string. There is no clear function that would do that, and the one that is close is marked as private, which may mean it might actually become private once WP fully goes PHP 5, so I wouldn't dare use it. Plus it uses regex.

      I think the key here is balance - try to balance out the extra step involved with how much you're saving by not including extra files.

  2. gestroud says:

    I found this post via your link on Weblog Tools Collection. It would make an excellent guest post there. Why not contact WLTC's owner and ask if it can be used as a Guest Post?

    http://weblogtoolscollection.com/contact-me/

    • gestroud, thanks, yeah I did contact Mark but since I already posted it here, I would need to modify it enough to be unique again, which is not going to happen. If he feels like linking here at some point, however, I will welcome it.

  3. Ken says:

    It's also good to note that in HTML5 you are explicitly allowed to use style tags in the body, and there is a new attribute, scoped, to apply the styles only to the parent element and its descendants.

    This is kool, but not yet implemented, but if you are using HTML5 early, you can now include styles in the content legitimately.

  4. Lester Chan says:

    Nice post, maybe you should add in the codex.wordpress.org as well. The only concern I have is that it may require some processing power for sites which have lots of post because it is looping through all the post and the post content to find a match. This will result in more memory needed

    • Thanks for stopping by, Lester.

      I do give a warning about the extra pass but if crafted carefully, it should be quite harmless. Additionally, it actually shouldn't use extra memory (except for a few KBs) because it's looping through already existing post data and not modifying anything.

      Also, I went ahead and edited a few codex pages to include info related to this post. Thanks for the suggestion.

  5. jlapitan says:

    this is a very nice article.. saw it on tweet by @themelab..

    why not try nettuts.com

    maybe you can write or rewrite this article.. 150$ each approved topic…

    • Hey j,

      Are you affiliated with NetTuts? As I mentioned before, I don't want to rewrite an article just so it could be included on another blog.

      I will give them full rights to repost it though, or post it as a guest blogger, or just link to it.

  6. Otto says:

    Using the_posts filter to look ahead is clever, but has some drawbacks.

    Mainly, the_posts happens before the wp_head call, but *only* for the default query. If I change my query later by using wp_query, or if I create other separate WP_Query's later, then the_posts will happen again, with different content, perhaps after the wp_head.

    Generally speaking, it's actually better to NOT optimize in this case and simply include your script all the time. Why? Browser caching.

    If we assume that your visitor is going to see at least one page that requires the script, then at some point he'll have to load the script into the browser. But that only happens one time, the rest of the time the script is already in their browser cache. So how much time do you really save them from doing this conditional loading? They have to load the thing anyway, generally. All that adding this conditional loading really does for you is to add a bunch of PHP execution in order to save some time that really isn't saved…

    This is unnecessary optimization. It's probably a de-optimization on most setups. I'd avoid doing lookahead unless you have a specific use case where it fits. It doesn't fit the general case.

  7. While this is an interesting approach with several real-world applications, I am concerned about attempting this approach while ignoring appropriate cache control settings. When properly configured, your server should never send JS and CSS files on every page request. There are several excellent reviews on setting appropriate expires and cache control settings via PHP and on Apache (through config files and .htaccess). Properly compressed – and combined and optimized if needed – you should never need to load the same file continously. In fact, if you use the Google-sourced jQuery and other libraries, some of the largest files may already be cached on the users browser.

  8. epsi says:

    Why not using php output buffer 'ob_get_contents()' for main content in template?

    Steps:
    1. Run main content in output buffer, e.g. $ob
    2. wp_head() somewherein your theme, e.g. in htmlhead.php
    3. echo $ob

    This will run every enqueue scripts/styles before the wp_head.

    While this approach needs template overhaul. This makes template cleaner.

  9. 11 Pings:
  10. Social comments and analytics for this post…

    This post was mentioned on Twitter by ArtemR: Just posted [Wordpress Plugin Development] How To Include CSS and JavaScript Conditionally And Only When Needed By …: http://ping.fm/DIM0S...

  11. [...] Dieser exzellente Artikel stellt eine verbesserte Lösung dieses Problems dar. Social [...]

  12. [...] This post was mentioned on Twitter by Donncha O Caoimh, wptavern, wptavern, andrea_r, ArtemR and others. ArtemR said: @weblogtooltips #Wordpress JS & CSS conditional include guide for developers: http://j.mp/5xa4bz Do you have any feedback? RT? [...]

  13. [...] Social comments and analytics for this post… This post was mentioned on Twitter by ArtemR: Just posted [ Wordpress Plugin Development] How To Include CSS and JavaScript Conditionally And Only When Needed By …: http://ping.fm/DIM0S. … It is run by Artem Russakovskii – a local San Francisco geek who currently works at Plaxo and enjoys hacking Android, PHP, CSS, Javascript, AJAX, Perl, and regular expressions, working on Wordpress plugins and tools , tweaking MySQL queries … See the original post:  [Wordpress Plugin Development] How To Include CSS and JavaScript … [...]

  14. [...] submission has been well received by plugin developers that have taken notice. The article explains how to include CSS and JavaScript conditionally so that the code is not loaded on every page of the site. If you think about it, there are many [...]

  15. [...] I'm wondering what your thoughts are on this article that other folks have looked highly upon. http://beerpla.net/2010/01/13/wordpr…-by-the-posts/ WPTavern Twitter Account | Personal Blog | WordPress Weekly [...]

  16. [...] nonsense.First of all, I'd like to thank everyone who read and gave their 2 cents about the [Wordpress Plugin Development] How To Include CSS and JavaScript Conditionally And Only When Needed … post. The article was well received and will hopefully spark some optimizations around loading [...]

  17. [...] How To Include CSS and JavaScript Conditionally And Only When Needed By The Posts [...]

  18. [...] tutorial on loading CSS and JavaScript and using WordPress queue functions for this. [Wordpress Plugin Development] How To Include CSS and JavaScript Conditionally And Only When Needed … VN:F [1.8.0_1031]Rating: 0.0/10 (0 votes [...]

  19. [...] Include CSS and Javascript conditionally [...]

Leave a Reply

Connect with Facebook