Performance: Enqueuing styles and scripts
This affects page load speed by controlling when and how CSS and JavaScript files load, impacting render blocking and bundle size.
Jump into concepts and practice - no test required
<?php
function theme_enqueue_assets() {
wp_enqueue_style('theme-style', get_stylesheet_uri());
wp_enqueue_script('theme-script', get_template_directory_uri() . '/script.js', [], null, true);
}
add_action('wp_enqueue_scripts', 'theme_enqueue_assets');<?php // Directly adding styles and scripts in header.php ?><link rel="stylesheet" href="style.css"> <script src="script.js"></script>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Directly adding <link> and <script> tags in header | Minimal DOM nodes added | Multiple reflows due to blocking | High paint cost due to delayed styles | [X] Bad |
| Using wp_enqueue_style and wp_enqueue_script with footer loading | Minimal DOM nodes added | Single reflow after styles load | Lower paint cost, faster LCP | [OK] Good |
wp_enqueue_style and wp_enqueue_script in WordPress?wp_enqueue_style and wp_enqueue_script are designed to add CSS and JS files safely to WordPress pages.style.css located in your theme folder?wp_enqueue_style. The URL should be built with get_template_directory_uri() plus the file path.wp_enqueue_script which is for JS, not CSS. wp_add_style('my-style', get_template_directory_uri() . '/style.css'); uses a non-existent function wp_add_style.functions.php?
function load_custom_scripts() {
wp_enqueue_script('custom-js', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'load_custom_scripts');function add_my_script() {
wp_enqueue_script('my-script', get_template_directory() . '/js/script.js');
}
add_action('wp_enqueue_scripts', 'add_my_script');get_template_directory() returns a server path, not a URL. For enqueuing scripts, a URL is needed, so get_template_directory_uri() should be used.wp_enqueue_scripts is correct. add_action is the right function to hook.main.css and theme.css. theme.css depends on main.css. Which code correctly enqueues both with dependency and versioning?theme.css depends on main.css, so theme-style must list main-style as a dependency.main-style first with no dependencies, then theme-style with main-style as dependency and proper versions. Other options reverse dependencies or omit them.