Safely Load Scripts and Styles in WordPress Themes

The correct way to include JavaScript and CSS in WordPress is through the wp_enqueue_scripts hook. This prevents duplication and ensures compatibility with themes and plugins.

Why Use Enqueuing Instead of Hardcoding?

Using proper WordPress functions to load assets ensures:

  • No Script Clashes: Avoids loading the same file more than once.
  • Correct Load Order: WordPress automatically manages dependencies.
  • Optimized Delivery: Assets are loaded where and when needed.

With wp_enqueue_script() and wp_enqueue_style(), your files are added cleanly to the frontend.

How to Add Scripts and Styles

Insert this in functions.php to load your CSS and JS:

function theme_assets_loader() {
    wp_enqueue_script('theme-main-js', get_template_directory_uri() . '/assets/js/main.js', array('jquery'), '1.0', true);
    wp_enqueue_style('theme-main-css', get_template_directory_uri() . '/assets/css/main.css', array(), '1.0');
}
add_action('wp_enqueue_scripts', 'theme_assets_loader');

Code Breakdown

  • Script: Depends on jQuery and loads in the footer.
  • Style: Loads the stylesheet with no dependencies.

Make sure your theme has the proper folder structure. Correct enqueuing helps prevent plugin clashes and improves page speed.

Final Thoughts

Use wp_enqueue_scripts for all frontend asset loading in WordPress. This is the recommended method for a robust, performance-friendly site.

See the official docs to explore more.

Leave a Comment

Your email address will not be published. Required fields are marked *

Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.