This article is part of a series created in partnership with SiteGround. Thank you for supporting the partners who make SitePoint possible.
In this article, you are going to learn how to load CSS styles and scripts only when your website needs them. This way your website will load faster and users who don’t visit the pages with the extra files won’t have to download unnecessary bytes in their browsers.
Why You Should Add Styles and Scripts the WordPress Way
If there is an anti-pattern in WordPress development, this is adding a
<head> section of the HTML document and call it a day.
This means that theme or plugin authors don’t know in advance which styles and scripts a specific installation is going to run, or in which order those resources are needed. For instance, let’s take the jQuery library. This library can be used by WordPress itself to handle Ajax requests and other tasks, by more than one plugin, and by the active theme.
If plugin and theme authors include the stylesheets and scripts they need by adding the appropriate tags directly inside the HTML document, this could open the doors to the possibility of conflicts, of resources being loaded multiple times and/or in the wrong order.
This is why you should always load styles and scripts following best practices as recommended by WordPress.org coding standards:
So that everything works harmoniously, it’s important that theme and plugins load scripts and stylesheets using the standard WordPress method. This will ensure the site remains efficient and that there are no incompatibility issues.
How to Use wp_enqueue_style and wp_enqueue_script
The barebone function to include your custom stylesheet into a theme looks like this:
wp_enqueue_style( $handle, $src, $deps, $ver, $media );
Only the first two parameters are obligatory, the others are optional.
$handleparameter is the name of your stylesheet. You can call it
$srcstands for the URL where the stylesheet is located
$depsparameter specifies if this stylesheet depends on another stylesheet to work correctly
$verdetermines the stylesheet’s version number. This can be useful for minimizing collisions
$mediastands for the media type the stylesheet is for, e.g., all, screen, print, etc.
As an example, the code to add a stylesheet named
portfolio.css to your WordPress website could look like this:
wp_enqueue_style( ‘portfolio’, get_template_directory_uri() . ‘/css/portfolio.css’,false,’1.1′,’screen’);
wp_enqueue_script($handle, $src, $deps, $ver, $in_footer)
The parameters are similar to those in
wp_enqueue_style, except for the last one, which sets a true or false value according to whether you want to place the
<script> tag in the
<header> section of your document.
Let’s say you’d like to add
portfolio.js to your website, here’s what the code would look like:
Continue reading %Conditional Tags to Load Styles and Scripts in WordPress%