17

Follow-up To Loading CSS And JS Conditionally


Posted by Artem Russakovskii on January 15th, 2010 in Programming, Wordpress

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 By The Posts post. The article was well received and will hopefully spark some optimizations around loading styles and scripts.

Here are some discussions and mentions around the web:

Sure, there are drawbacks to this method and it does require some more processing on the backend and it's not for everyone, which is why we should always strive for an even better solution.

I stand by my point of view that, for instance, my dedicated gallery shouldn't load for people who will never even go see my photos.

I think an ideal solution would be for WP core developers, who had a lot of experience designing WordPress' internals and who know what can work and what can't, perhaps Matt included, to get together and think about a better solution really hard.

Conditional loading similar to the one discussed here is already possible in the admin area, which creates dynamic hooks by appending page ids to 'admin_print_styles' and 'admin_print_scripts'. It is, however, still not good enough to be used more generically because those hooks rely on the page you are on, rather than the content of that page.

Another possibility is using a PHP technique called output buffering (ob_start(), ob_flush(), etc) that grants second chances to data that had already been echoed. It intercepts all echo and print calls and redirects them into a memory buffer, so instead of printing data to the page right away, you can now modify the header even if it had already been processed. It's like giving it a second chance.

Would it work for WordPress? I am not sure but I sure could use your feedback, devs.

Update: Scribu, a WordPress master, came up with the approach that would at least handle loading JS, as it would put it in the footer, which can be done after the posts have been parsed.

His approach doesn't handle CSS which is why I decided to seek another solution but it doesn't require an extra pass through the posts and it benefits from using the shortcode API instead of stripos() or some hacky regex you'd need to come up with.

It's a great compromise for developers who do not want to take the approach I outlined in the article linked at the top of this page.

● ● ●
Artem Russakovskii is a San Francisco programmer and blogger. Follow Artem on Twitter (@ArtemR) or subscribe to the RSS feed.

In the meantime, if you found this article useful, feel free to buy me a cup of coffee below.