---
title: "Enqueue Scripts and Styles: Add JavaScript and CSS the Right Way"
description: "If you have ever added a JavaScript snippet directly to your WordPress theme and watched your site break, you already know the problem this article solves. The correct way to…"
url: "https://wondanation.com/enqueue-scripts-wordpress/"
type: "post"
date: "2026-11-29T02:05:09+01:00"
modified: "2026-11-29T06:52:02+01:00"
author: "Digital Hub Team"
---

# Enqueue Scripts and Styles: Add JavaScript and CSS the Right Way

If you have ever added a JavaScript snippet directly to your WordPress theme and watched your site break, you already know the problem this article solves. The correct way to enqueue scripts WordPress provides is through a built-in system that manages how files load, in what order, and whether they conflict with other plugins or themes.

This guide walks you through that system from the ground up. You will learn what enqueueing actually means, why it matters for performance and stability, and exactly how to add JavaScript and CSS to your WordPress site without touching things you should not touch.

No advanced coding background required. Just a willingness to follow steps carefully.

![broken vs properly functioning wordpress site after script enqueueing](https://wns.staging.wondahost.com/wp-content/uploads/2026/08/Broken-vs-properly-functioning-WordPress-site-after-script-enqueueing.png "Enqueue Scripts and Styles: Add JavaScript and CSS the Right Way")

### **What “Enqueue” Actually Means (And Why WordPress Does It This Way)**

The word “enqueue” simply means “to add to a queue.” In WordPress, that queue is a list of scripts and stylesheets that get loaded on your site in a specific, controlled order.

Before WordPress introduced this system, developers added JavaScript and CSS directly inside theme files using raw HTML tags. That approach caused serious problems: the same library (like jQuery) would load multiple times from different plugins, scripts would conflict with each other, and sites would slow down or break unpredictably.

WordPress solved this by creating a central registration and loading system. Every script and stylesheet goes through two steps:

- **Register:** You tell WordPress a file exists and give it a name (a “handle”).
- **Enqueue:** You tell WordPress to actually load that file on the page.

Think of it like a restaurant. Registering a dish is adding it to the menu. Enqueueing it is ordering it for the table. You can have items on the menu that never get ordered, which is useful when you only want certain scripts loading on certain pages.

This system prevents duplicate loading, manages dependencies (making sure jQuery loads before any plugin that needs it), and gives you precise control over performance.

**Key takeaway:** Enqueueing is not just best practice. It is the only reliable way to add JavaScript and CSS in WordPress without creating conflicts.

### **The Two Core Functions You Need to Know**

WordPress gives you two primary functions for adding assets:

- wp\_enqueue\_script() for JavaScript files
- wp\_enqueue\_style() for CSS stylesheets

Both functions follow a similar pattern. Here is the basic structure for each:

```
wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer );
wp_enqueue_style( $handle, $src, $deps, $ver, $media );
```

Here is what each parameter means in plain language:

| Parameter | What It Does | Example Value |
| --- | --- | --- |
| $handle | A unique nickname for your file | ‘my-custom-script’ |
| $src | The full URL to the file | get\_template\_directory\_uri() . ‘/js/custom.js’ |
| $deps | Other scripts this one needs to run | array(‘jquery’) |
| $ver | Version number (for cache busting) | ‘1.0.0’ |
| $in\_footer | Load in footer instead of header? | true |

For wp\_enqueue\_style(), the last parameter is $media instead of $in\_footer. This lets you target specific media types like ‘screen’ or ‘print’. Most of the time you will leave it as ‘all’.

You almost always want $in\_footer set to true for JavaScript. Loading scripts in the footer means your page content appears to visitors before the browser starts downloading JavaScript files, which makes your site feel faster.

![wordpress page load timeline comparing header and footer scripts](https://wns.staging.wondahost.com/wp-content/uploads/2026/08/WordPress-page-load-timeline-comparing-header-and-footer-scripts.png "Enqueue Scripts and Styles: Add JavaScript and CSS the Right Way")

**Key takeaway:** Learn these two functions and their parameters. Everything else in this guide builds on them.

### ****Where to Enqueue Scripts in WordPress: The Right Hook****

You do not call wp\_enqueue\_script() or wp\_enqueue\_style() directly in your theme files. You wrap them inside a function and attach that function to the correct WordPress action hook.

The hook you need is wp\_enqueue\_scripts. Despite the name, it handles both scripts and styles.

Here is the basic template:

```
function wns_add_custom_assets() {
    wp_enqueue_style(
        'wns-main-style',
        get_template_directory_uri() . '/css/custom.css',
        array(),
        '1.0.0',
        'all'
    );
    wp_enqueue_script(
        'wns-main-script',
        get_template_directory_uri() . '/js/custom.js',
        array( 'jquery' ),
        '1.0.0',
        true
    );
}
add_action( 'wp_enqueue_scripts', 'wns_add_custom_assets' );
```

You add this code to your theme’s functions.php file or, better yet, to a site-specific plugin (more on that later).

A quick note on get\_template\_directory\_uri(): this function returns the URL to your theme folder. If you are using a child theme and want to reference the child theme’s files, use get\_stylesheet\_directory\_uri() instead.

![wordpress functions.php showing an enqueue function](https://wns.staging.wondahost.com/wp-content/uploads/2026/08/WordPress-functions.php-showing-an-enqueue-function.png "Enqueue Scripts and Styles: Add JavaScript and CSS the Right Way")

#### **What About the Admin Area?**

The wp\_enqueue\_scripts hook only runs on the front end of your site. If you need to add scripts to the WordPress admin dashboard, use the admin\_enqueue\_scripts hook instead. For the login page, use login\_enqueue\_scripts.

```
function wns_admin_scripts() {
    wp_enqueue_script(
        'wns-admin-script',
        get_template_directory_uri() . '/js/admin.js',
        array(),
        '1.0.0',
        true
    );
}
add_action( 'admin_enqueue_scripts', 'wns_admin_scripts' );
```

**Key takeaway:** Always use the wp\_enqueue\_scripts hook for front-end assets. Never call enqueue functions outside of a hooked function.

### **Step-by-Step: Adding Your First Custom Script and Stylesheet**

Let us walk through a real example. You want to add a custom JavaScript file and a custom CSS file to your WordPress site.

**Step 1: Create your files**

Inside your theme folder, create two new files:

- /js/custom.js
- /css/custom.css

You can use an FTP client or your hosting file manager to do this. If you are using a child theme (which you should be for any customizations), create them inside your child theme folder.

**Step 2: Open functions.php**

Navigate to your child theme folder and open functions.php. If the file does not exist yet, create it. Every functions.php file must start with an opening PHP tag:

```
<?php
```

**Step 3: Add the enqueue function**

Paste this code into your functions.php file:

```
function wns_load_custom_assets() {
    // Load custom CSS
    wp_enqueue_style(
        'wns-custom-style',
        get_stylesheet_directory_uri() . '/css/custom.css',
        array(),
        '1.0.0'
    );
    // Load custom JavaScript (depends on jQuery, loads in footer)
    wp_enqueue_script(
        'wns-custom-script',
        get_stylesheet_directory_uri() . '/js/custom.js',
        array( 'jquery' ),
        '1.0.0',
        true
    );
}
add_action( 'wp_enqueue_scripts', 'wns_load_custom_assets' );
```

**Step 4: Save and verify**

Save the file, then visit your site. Right-click the page and choose “View Page Source.” Search for custom.css and custom.js. You should see them referenced in the HTML output. Your CSS link should appear inside the \<head> tag, and your JavaScript should appear just before the closing \</body> tag.

![page source showing custom css and javascript files](https://wns.staging.wondahost.com/wp-content/uploads/2026/08/Page-source-showing-custom-CSS-and-JavaScript-files.png "Enqueue Scripts and Styles: Add JavaScript and CSS the Right Way")

**Step 5: Test functionality**

Add a small test to your JavaScript file, like console.log(‘Custom script loaded’);, then open your browser’s developer tools and check the Console tab. If you see the message, your script is loading correctly.

**Key takeaway:** This five-step process is the foundation for every custom script you will ever add to WordPress. Master it once and it becomes second nature.

### **Loading Third-Party Libraries the Right Way**

Sometimes you need to load an external library, like a slider, an animation tool, or a payment SDK. You have two options: host the file yourself, or load it from a CDN (Content Delivery Network, meaning the file is served from the library’s own servers).

#### **Loading a Self-Hosted Library**

Download the library file, place it in your theme’s /js/ folder, and enqueue it exactly as shown above.

```
wp_enqueue_script(
    'wns-slick-slider',
    get_stylesheet_directory_uri() . '/js/slick.min.js',
    array( 'jquery' ),
    '1.8.1',
    true
);
```

#### **Loading from an External CDN**

For external files, simply replace the local path with the full CDN URL:

```
wp_enqueue_script(
    'wns-gsap',
    'https://cdnjs.cloudflare.com/ajax/libs/gsap/3.12.2/gsap.min.js',
    array(),
    '3.12.2',
    true
);
```

#### **Using WordPress’s Built-In jQuery**

WordPress ships with its own version of jQuery. You should never load jQuery separately using wp\_enqueue\_script or by adding a script tag manually. Instead, declare it as a dependency and WordPress will load its built-in version automatically:

```
wp_enqueue_script(
    'wns-my-script',
    get_stylesheet_directory_uri() . '/js/my-script.js',
    array( 'jquery' ),  // This tells WordPress to load jQuery first
    '1.0.0',
    true
);
```

This is one of the most important performance and conflict-prevention rules in WordPress development. Duplicate jQuery loading is behind a surprising number of plugin conflicts. Properly declaring your dependencies also relates to broader site stability. For tips on tracking down those issues, see our guide on [Plugin Conflicts: How to Find and Resolve Compatibility Issues](https://wns.staging.wondahost.com/wordpress-plugin-conflicts/).

**Key takeaway:** Always declare dependencies explicitly. Let WordPress manage loading order instead of guessing it yourself.

### **Conditional Loading: Only Load Scripts Where You Need Them**

Here is where proper enqueueing really earns its keep. Loading every script on every page is wasteful. A slider script on your contact page serves no purpose. An analytics script on your admin pages adds noise.

WordPress gives you conditional tags to control exactly where scripts load.

#### **Load Only on the Homepage**

```
function wns_conditional_scripts() {
    if ( is_front_page() ) {
        wp_enqueue_script(
            'wns-homepage-slider',
            get_stylesheet_directory_uri() . '/js/slider.js',
            array( 'jquery' ),
            '1.0.0',
            true
        );
    }
}
add_action( 'wp_enqueue_scripts', 'wns_conditional_scripts' );
```

#### **Load Only on Single Posts**

```
if ( is_single() ) {
    wp_enqueue_script( 'wns-reading-progress', ... );
}
```

#### **Load Only on Specific Pages**

```
if ( is_page( 'contact' ) ) {
    wp_enqueue_script( 'wns-contact-form-script', ... );
}
```

#### **Common Conditional Tags**

| Conditional Tag | When It Returns True |
| --- | --- |
| is\_front\_page() | The site’s homepage |
| is\_single() | Any single blog post |
| is\_page() | Any static page |
| is\_archive() | Category, tag, or date archive |
| is\_woocommerce() | Any WooCommerce page |
| is\_user\_logged\_in() | Only for logged-in users |

Reducing unnecessary script loads directly improves your Core Web Vitals scores and page speed. This connects to broader optimization work covered in our guide on Minify CSS and JavaScript in WordPress: Reduce File Sizes.

**Key takeaway:** Conditional loading is not optional for serious sites. Every unnecessary script load costs your visitors time and costs you rankings.

### **Passing PHP Data to JavaScript with wp\_localize\_script**

Sometimes your JavaScript needs information that only PHP knows, like your site’s URL, a nonce (a security token WordPress uses to verify requests), or user-specific data.

The function wp\_localize\_script() bridges that gap. It creates a JavaScript object that your script can access, populated with data you pass from PHP.

Here is how it works:

```
function wns_load_ajax_script() {
    wp_enqueue_script(
        'wns-ajax-handler',
        get_stylesheet_directory_uri() . '/js/ajax-handler.js',
        array( 'jquery' ),
        '1.0.0',
        true
    );
    wp_localize_script(
        'wns-ajax-handler',    // Must match the handle above
        'wnsAjaxData',         // The JavaScript variable name
        array(
            'ajaxurl' => admin_url( 'admin-ajax.php' ),
            'nonce'   => wp_create_nonce( 'wns_ajax_nonce' ),
            'siteurl' => get_site_url(),
        )
    );
}
add_action( 'wp_enqueue_scripts', 'wns_load_ajax_script' );
```

Inside your JavaScript file, you can now access these values:

javascript

console.log( wnsAjaxData.siteurl ); // Outputs your site URL

console.log( wnsAjaxData.nonce ); // Outputs the security nonce

The key rule: wp\_localize\_script() must be called after the corresponding wp\_enqueue\_script() call, and it must use the same handle.

**Key takeaway:** Never hardcode your site URL or security tokens directly in JavaScript files. Use wp\_localize\_script() to pass them safely from PHP.

### **Best Practices for Scaling and Maintaining Clean Code**

As your site grows and your functions.php file fills up, organization becomes critical. Here are the practices that keep things manageable.

#### **Use a Site-Specific Plugin Instead of functions.php**

Your functions.php file is tied to your theme. If you switch themes, all your custom code disappears. A site-specific plugin solves this. Create a simple plugin file:

```
<?php
/**
 * Plugin Name: WNS Site Functions
 * Description: Site-specific customizations for WNS Digital Hub
 * Version: 1.0.0
 */
function wns_load_custom_assets() {
    // All your enqueue code here
}
add_action( 'wp_enqueue_scripts', 'wns_load_custom_assets' );
```

Save this file as wns-site-functions.php inside its own folder in /wp-content/plugins/, then activate it from the WordPress Plugins menu. Your customizations now survive any theme change.

#### **Use Version Numbers for Cache Busting**

When you update a script, browsers may still serve the old cached version to visitors. Incrementing your version number forces browsers to download the new file:

```
wp_enqueue_script( 'wns-script', $src, $deps, '1.0.1', true ); // Was 1.0.0
```

#### **Group Related Assets Together**

Keep one enqueue function per logical area of your site. For example:

```
function wns_global_assets() { /* Loads on every page */ }
function wns_homepage_assets() { /* Only homepage */ }
function wns_woocommerce_assets() { /* Only WooCommerce pages */ }
```

This makes debugging much faster when something breaks.

For related tips on keeping your CSS organized and maintainable, see our article on WordPress Custom CSS: Add Styling Without Breaking Your Theme.

#### **Dequeue Unwanted Scripts**

Sometimes plugins or themes load scripts you do not need. You can remove them with wp\_dequeue\_script():

```
function wns_remove_unused_scripts() {
    wp_dequeue_script( 'contact-form-7' ); // Example: remove CF7 scripts globally
}
add_action( 'wp_enqueue_scripts', 'wns_remove_unused_scripts', 20 );
```

Note the priority of 20. This runs your dequeue function after most plugins have added their scripts (which usually happens at the default priority of 10), so your removal actually takes effect.

![wordpress plugins page showing an active site functions plugin](https://wns.staging.wondahost.com/wp-content/uploads/2026/08/WordPress-Plugins-page-showing-an-active-Site-Functions-plugin.png "Enqueue Scripts and Styles: Add JavaScript and CSS the Right Way")

**Key takeaway:** Treat your codebase like a business asset. Organized, well-commented code saves hours of debugging time as your site scales.

### **Frequently Asked Questions**

 **What is the difference between wp\_register\_script and wp\_enqueue\_script?** 

wp\_register\_script() adds a script to WordPress’s registry without loading it. wp\_enqueue\_script() both registers and queues the script for loading. Use wp\_register\_script() when you want to define a script once and then conditionally enqueue it in different places. For most simple use cases, wp\_enqueue\_script() alone is all you need.  

 Can I add JavaScript to WordPress without using functions.php? 

Yes, and the right way to add JavaScript to WordPress outside of functions.php is through a site-specific plugin, covered in the scaling section above. What you should avoid is adding raw \<script> tags directly into theme template files, as this bypasses the dependency management system and causes loading order conflicts and duplicate library loading.

 Why is my enqueued script not showing up on the page?  

Check four things: confirm the file path in $src is correct, verify the function is hooked to wp\_enqueue\_scripts, make sure there are no PHP syntax errors in your functions.php file, and confirm your theme calls wp\_head() and wp\_footer() in its template files. Without those template calls, WordPress has nowhere to output the script tags.  

 How do I load scripts only for logged-in users?  

Wrap your enqueue call in an is\_user\_logged\_in() check inside your hooked function. For example: if ( is\_user\_logged\_in() ) { wp\_enqueue\_script(…); }. This is useful for member features, personalization scripts, or analytics you only want to run for registered users.  

 Does enqueueing scripts affect my site’s SEO?  

Yes, indirectly. Properly enqueued scripts load in the footer by default, which improves page rendering speed and Core Web Vitals scores. Both are Google ranking factors. Poorly loaded scripts that block rendering can hurt your search performance. For more on how site performance connects to search visibility, see our guide on \[Google Search Console for WordPress: Setup and Daily Use Guide\].  

 What is a script handle and does it have to be unique?  

A handle is the nickname you give a script or stylesheet in the first parameter of wp\_enqueue\_script() or wp\_enqueue\_style(). It must be unique across your entire WordPress installation, including all active plugins. Use a prefix specific to your site or brand (like wns-) to avoid collisions with plugin handles.  

 Can I enqueue scripts in Gutenberg blocks?  

Yes, but the process is different. Block editor scripts use register\_block\_type() and its editor\_script, editor\_style, and style attributes rather than the standard wp\_enqueue\_scripts hook. This is covered in detail in our article on \[Advanced Gutenberg Techniques: Columns, Groups, and Nested Blocks\].  

### **What to Do Next**

You now have a solid working understanding of how WordPress loads scripts and styles. Here is how to put that knowledge into action immediately.

**1\. Audit your current scripts.** Open your site in a browser, right-click, and view the page source. Count how many times jQuery or other common libraries appear. If you see duplicates, you have a conflict to resolve. Our article on [Plugin Conflicts: How to Find and Resolve Compatibility Issues](https://wns.staging.wondahost.com/wordpress-plugin-conflicts/) walks you through the diagnostic process.

**2\. Create a site-specific plugin.** If you currently have custom code living in your theme’s functions.php, migrate it to a site-specific plugin this week. It takes less than 20 minutes and protects your work from being wiped out by a theme change.

**3\. Implement conditional loading on your heaviest pages.** Identify the two or three scripts on your site that only serve specific pages (sliders, form validators, popup triggers). Add conditional tags so they only load where needed. Then run a page speed test on Google PageSpeed Insights before and after to see the difference.

**4\. Explore related customization techniques.** Enqueueing scripts is one piece of a larger customization toolkit. Expand your skills with [Custom Fields in WordPress: Add Extra Data to Your Content](https://wns.staging.wondahost.com/custom-fields-in-wordpress/) for data management, and review [SSL Certificates for WordPress: HTTPS Setup and Troubleshooting](https://wns.staging.wondahost.com/ssl-certificate-wordpress/) to make sure all your externally loaded scripts are being served over HTTPS to avoid mixed content warnings.
