Search code examples
phpcsswordpressincludestyles

Why does people use wp_register_style and wp_enque_style? (Wordpress)


I see wp_register_style and wp_enqueue_style everywhere whenver I check other Wordpress plugin files.

public function cmc_shortcode_style() {
  wp_register_style( 'cmc-shortcodes-style', plugins_url( 'assets/css/cmc-shortcodes.css', __FILE__ ), array(), '1.0.0', 'all' );
  wp_enqueue_style( 'cmc-shortcodes-style' );
}

add_action( 'wp_enqueue_scripts', array( $this, 'cmc_shortcode_style' ) );

I also read the Wordpress document and found out that it works similar as include or require.
Then why don't they just use include?

include (ABSPATH . '/wp-content/plugins/cmc/assets/css/cmc-shortcodes.css');

Hmm...There would be a definite reason 'cause everyone is using it.


Solution

  • Those functions are used for several reasons:

    • Dequeuing - Whatever is enqueued by someone can also be dequeued by someone later
    • Bundling - There are many plugins that take all of the scripts and styles that are enqueued and spit out optimized versions
    • CDN - Similar to the previous, there are plugins that are able to offload enqueue assets to a CDN
    • Inlining - Same as the previous again, some plugins might inline your resource instead of having the browser manually request it
    • Security - A plugin could use this information to apply SRI to the HTML
    • Dependencies - The dependency option allows you to further say "if you use this, also include these first".
      • The entire jQuery system is a great example. If you write code that uses jQuery, you can enqueue it with jquery as a dependency and WordPress will make sure your JS is loaded later. Similarly, if you need Masonry, you can use jquery-masonry and both jQuery and Masonry will be loaded in the correct order
    • Cache busting - By using the version option you can specify an argument that will be appended to the query string which allows for efficient client-side caching with a simple override

    That's just off the top of my head, probably a bunch more