DevinVinson / WordPress-Plugin-Boilerplate

[WordPress] A foundation for WordPress Plugin Development that aims to provide a clear and consistent guide for building your plugins.
http://wppb.io
7.68k stars 2.27k forks source link

Lazy load scripts and stylesheets #451

Open tlhackque opened 7 years ago

tlhackque commented 7 years ago

I've noticed that many plugins unconditionally load their JS and CSS into every page.

This is bad for page size and load times, as often these are only needed on pages that require the plugin. E.g. when a shortcode is invoked on the page (whether by template, page, or post).

Of course, some plugins do apply to every page - in those cases, unconditionally loading JS and CSS is fine. But loading them for a rarely-used code - e.g. a map, media player, slideshow or ... can be very expensive. For example, one plugin adds several seconds to every page because it invokes a Google API that requires an authentication exchange. Yet that plugin is likely to be used on less than 1% of the pages on a typical site. And, of course, extra requests and bandwidth are always a bad thing - especially on mobile devices. This is particularly distressing when a visitor first hits a site's home/landing page; as mom says, "first impressions count".

I'm not a WP internals expert (or plugin author), but from browsing the internet, getting lazy load right in all cases can be tricky. (Where "right" includes always loading when required; getting CSS into HEAD; minimizing detection overhead; at most once semantics, optimizing HTTP/2 PUSH,...)

It would be helpful if the Boilerplate plugin demonstrated best practices for lazy loading scripts and stylesheets, especially for those only needed when a specific shortcode (or shortcode attribute) is present.

This would help authors to get this right the first time - and save performance sensitive users from playing wack-a-mole with each plugin that we use.

Thanks.

dingo-d commented 7 years ago

A PR could be made that adds $hook parameter in the enqueue functions

https://github.com/DevinVinson/WordPress-Plugin-Boilerplate/blob/7af6de6dd2347d3a7cbe53cd449ab5c723de0dd0/plugin-name/admin/class-plugin-name-admin.php#L85

That should be then used to enqueue scripts/styles only on the pages you need.