Title: JavaScript in Themes
Published: 25 May 2024
Last modified: 31 July 2024

---

[Home](https://learn.wordpress.org)[Courses](https://learn.wordpress.org/courses/)
[Intermediate Theme Developer](https://learn.wordpress.org/course/intermediate-theme-developer/)
JavaScript in Themes

 [ Exit Course ](https://learn.wordpress.org/course/intermediate-theme-developer/)

 1.   a.  [   Global theme settings  ](https://learn.wordpress.org/lesson/global-theme-settings/)
         [Preview](https://learn.wordpress.org/lesson/global-theme-settings/)
      b.  [   Block theme styles  ](https://learn.wordpress.org/lesson/block-theme-styles/)
         [Preview](https://learn.wordpress.org/lesson/block-theme-styles/)
      c.  [   Templates  ](https://learn.wordpress.org/lesson/custom-templates/) [Preview](https://learn.wordpress.org/lesson/custom-templates/)
      d.  [   Theme Patterns  ](https://learn.wordpress.org/lesson/theme-patterns/) [Preview](https://learn.wordpress.org/lesson/theme-patterns/)
      e.  [   Style Variations  ](https://learn.wordpress.org/lesson/style-variations/)
         [Preview](https://learn.wordpress.org/lesson/style-variations/)
 2.   5 lessons
 3.   a.  [   Template overview  ](https://learn.wordpress.org/lesson/template-overview/)
         [Preview](https://learn.wordpress.org/lesson/template-overview/)
      b.  [   Template Hierarchy  ](https://learn.wordpress.org/lesson/template-hierarchy/)
         [Preview](https://learn.wordpress.org/lesson/template-hierarchy/)
      c.  [   Template parts  ](https://learn.wordpress.org/lesson/template-parts-4/) 
         [Preview](https://learn.wordpress.org/lesson/template-parts-4/)
 4.   3 lessons
 5.   a.  [   Custom functionality  ](https://learn.wordpress.org/lesson/custom-functionality/)
         [Preview](https://learn.wordpress.org/lesson/custom-functionality/)
      b.  [   Including assets  ](https://learn.wordpress.org/lesson/including-assets/)
         [Preview](https://learn.wordpress.org/lesson/including-assets/)
      c.  [   Block stylesheets  ](https://learn.wordpress.org/lesson/block-stylesheets/)
         [Preview](https://learn.wordpress.org/lesson/block-stylesheets/)
      d.  [   Block style variations  ](https://learn.wordpress.org/lesson/block-style-variations/)
         [Preview](https://learn.wordpress.org/lesson/block-style-variations/)
      e.  [   Block variations  ](https://learn.wordpress.org/lesson/block-variations/)
         [Preview](https://learn.wordpress.org/lesson/block-variations/)
 6.   5 lessons
 7.   a.  [   Introduction to Classic themes  ](https://learn.wordpress.org/lesson/introduction-to-classic-themes/)
         [Preview](https://learn.wordpress.org/lesson/introduction-to-classic-themes/)
      b.  [   The Loop  ](https://learn.wordpress.org/lesson/the-loop/) [Preview](https://learn.wordpress.org/lesson/the-loop/)
      c.  [   Theme options  ](https://learn.wordpress.org/lesson/theme-options/) [Preview](https://learn.wordpress.org/lesson/theme-options/)
      d.  [   theme.json in Classic themes  ](https://learn.wordpress.org/lesson/theme-json-in-classic-themes/)
         [Preview](https://learn.wordpress.org/lesson/theme-json-in-classic-themes/)
      e.  [   Converting a Classic theme to a Block theme  ](https://learn.wordpress.org/lesson/converting-a-classic-theme-to-a-block-theme/)
         [Preview](https://learn.wordpress.org/lesson/converting-a-classic-theme-to-a-block-theme/)
 8.   5 lessons
 9.   a.  [   Best practices for developing an accessible theme  ](https://learn.wordpress.org/lesson/best-practices-for-developing-an-accessible-theme/)
         [Preview](https://learn.wordpress.org/lesson/best-practices-for-developing-an-accessible-theme/)
      b.  [   Tools for testing theme accessibility  ](https://learn.wordpress.org/lesson/tools-for-testing-theme-accessibility/)
         [Preview](https://learn.wordpress.org/lesson/tools-for-testing-theme-accessibility/)
 10.  2 lessons
 11.  a.  [   Themes and user privacy  ](https://learn.wordpress.org/lesson/themes-and-user-privacy/)
         [Preview](https://learn.wordpress.org/lesson/themes-and-user-privacy/)
 12.  1 lesson
 13.  a.  [   Child themes  ](https://learn.wordpress.org/lesson/child-themes/) [Preview](https://learn.wordpress.org/lesson/child-themes/)
      b.  [   UI Best Practices  ](https://learn.wordpress.org/lesson/ui-best-practices/)
         [Preview](https://learn.wordpress.org/lesson/ui-best-practices/)
      c.  [   JavaScript in Themes  ](https://learn.wordpress.org/lesson/javascript-in-themes/)
         [Preview](https://learn.wordpress.org/lesson/javascript-in-themes/)
      d.  [   Build Process  ](https://learn.wordpress.org/lesson/build-process/) [Preview](https://learn.wordpress.org/lesson/build-process/)
      e.  [   Plugin API hooks  ](https://learn.wordpress.org/lesson/plugin-api-hooks/)
         [Preview](https://learn.wordpress.org/lesson/plugin-api-hooks/)
      f.  [   Testing your theme  ](https://learn.wordpress.org/lesson/testing-your-theme/)
         [Preview](https://learn.wordpress.org/lesson/testing-your-theme/)
 14.  6 lessons
 15.  a.  [   The WordPress.org Theme Directory  ](https://learn.wordpress.org/lesson/the-wordpress-org-theme-directory/)
         [Preview](https://learn.wordpress.org/lesson/the-wordpress-org-theme-directory/)
      b.  [   Required theme files  ](https://learn.wordpress.org/lesson/required-theme-files/)
         [Preview](https://learn.wordpress.org/lesson/required-theme-files/)
      c.  [   Preparing your theme for submission  ](https://learn.wordpress.org/lesson/preparing-your-theme-for-submission/)
         [Preview](https://learn.wordpress.org/lesson/preparing-your-theme-for-submission/)
      d.  [   Submitting your theme to WordPress.org  ](https://learn.wordpress.org/lesson/submitting-your-theme-to-wordpress-org/)
         [Preview](https://learn.wordpress.org/lesson/submitting-your-theme-to-wordpress-org/)
      e.  [   Updating your theme  ](https://learn.wordpress.org/lesson/updating-your-theme/)
         [Preview](https://learn.wordpress.org/lesson/updating-your-theme/)
 16.  5 lessons

### Advanced Theme Development

# JavaScript in Themes

JavaScript is a programming language that is used to add interactivity to web pages.

Theme developers will often use JavaScript to provide interactivity, animation, 
or other enhancements to their themes.

While using JavaScript can help to make your theme more engaging and interactive,
it can also introduce potential issues if not used correctly.

In this lesson, you’ll learn about some best practices for using JavaScript in your
WordPress theme

You will learn about using third-party JavaScript libraries, some best practices
to follow when writing JavaScript, whether or not you should use jQuery, and where
to find more information.

## JavaScript libraries

If you need to use any third-party JavaScript libraries in your theme, make sure
to check whether it’s already available via the WordPress install.

WordPress includes several JavaScript libraries that you can use. These libraries
are included with WordPress and are available for you to use in your theme.

A common mistake made by beginning theme developers is to bundle their theme with
their own version of the library.

However, this may conflict with plugins that enqueue the version bundled with WordPress.

You can find a full list of the default Scripts and JavaScript Libraries included
and registered by WordPress in the [wp_enqueue_scripts](https://developer.wordpress.org/reference/functions/wp_enqueue_script/#default-scripts-and-js-libraries-included-and-registered-by-wordpress)
function reference.

Make sure your theme is compatible with the version of your favorite library included
with WordPress.

## Writing JavaScript

JavaScript is growing in popularity on the web, and over the years the language 
has improved to be able to do a variety of tasks. This means that for more common
tasks, you may not need to use a JavaScript library at all, and can just write plain
JavaScript.

Here are some things to consider when writing your JavaScript:

 1. Try to avoid using global variables.

Global variables are available throughout the entirety of your code, regardless 
of scope. This means you can access and modify these variables from anywhere in 
your code, whether inside or outside of functions.

    ```javascript
    let greeting = "Hello, World!";
    function greet() {
      console.log(greeting);
    }
    greet(); // Outputs: "Hello, World!"
    ```

To avoid using global variables, you can use a number of alternatives, but the most
straightforward is to use an Immediately Invoked Function Expression (IIFE). This
allows you to define variables in a local scope, preventing them from polluting 
the global namespace.

    ```wp-block-code
    (function() {
        var greeting = "Hello, World!";
        console.log(greeting);
    })(); // Outputs: "Hello, World!"
    ```

 2. Keep your JavaScript unobtrusive

Make sure your JavaScript doesn’t interfere with the content of the page or produce
unnecessary errors. This means that your JavaScript should be separate from your
HTML, and should not rely on specific elements or classes in your HTML.

For example, if you need to add a click event to a button, you should use the `addEventListener()`
method to add the event listener, rather than using the `onclick` attribute in the
HTML. Additionally, you should check that the element exists on the page before 
adding the event listener.

    ```javascript
    (function() {
        let button = document.getElementById('myButton');
        if (button) {
            button.addEventListener('click', function() {
                alert('Button clicked!');
            });
        }
    })(); 
    ```

 3. Use a coding standard.

Using a coding standard can help to ensure that your code is consistent and easy
to read. WordPress has a [JavaScript Coding Standard](https://developer.wordpress.org/coding-standards/wordpress-coding-standards/javascript/)
that you can use to ensure that your code is consistent with the rest of the WordPress
codebase.

 4. Validate and Lint Your Code

Use a linter to check your code for errors and potential issues. This can help to
catch bugs early, and ensure that your code is consistent and easy to read.

[ESLint](https://eslint.org/) is a popular linter for JavaScript and can be used
to check your code for errors and potential issues. It is possible to configure 
your theme to use EsLint to check your JavaScript code via the @wordpress/scripts
[package](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-scripts/).

 5. Ensure your theme works without JavaScript

Ensure your site theme works without JavaScript first – then add JavaScript to provide
additional capabilities. This is a form of [Progressive Enhancement](https://developer.mozilla.org/en-US/docs/Glossary/Progressive_Enhancement),
which is a strategy that puts emphasis on web content first, allowing everyone to
access the basic content and functionality of a web page.

 6. Asset loading

Use [Lazy loading](https://developer.mozilla.org/en-US/docs/Web/Performance/Lazy_loading)
for assets that aren’t immediately required. To do this, identify resources that
are not critical for the content and load these only when needed.

## jQuery

jQuery is a JavaScript library that saw an increased use in the early days of web
development. However, with the improvements in JavaScript, it is often no longer
necessary to use jQuery for many common tasks.

Don’t use jQuery if you don’t need to — [You might not need jQuery](https://youmightnotneedjquery.com/)
is a great site that shows you how to do many of these common tasks with plain JavaScript.

For example, if you need to select an element by its ID, you can use the `document.
getElementById()` method in plain JavaScript.

    ```javascript
    // jQuery
    $( "#myElement" );

    // Plain JavaScript
    document.getElementById( 'myElement' );
    ```

Another good example is if you need to make an AJAX request, you can use the `fetch()`
method in plain JavaScript, or better yet, the WordPress [apiFetch](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-api-fetch/)
package.

    ```javascript
    // jQuery
    $.ajax({
      url: 'https://example.com/wp-json/wp/v2/posts',
      success: function( data ) {
          console.log( data );
      }
    });

    // Plain JavaScript
    fetch('https://example.com/wp-json/wp/v2/posts')
      .then(data => console.log(data));


    // apiFetch
    apiFetch( { path: '/wp/v2/posts' } ).then( posts => {
        console.log( posts );
    } );
    ```

If you must use jQuery in your theme, you should use the version of jQuery that 
is included with WordPress.

When enqueuing your theme’s scripts, you should specify jQuery as a dependency, 
by including it in the dependencies array.

    ```javascript
    add_action( 'wp_enqueue_scripts', 'my_theme_scripts' );
    function my_theme_scripts() {
        wp_enqueue_script( 
            'my-script', 
            get_template_directory_uri() . '/js/my-script.js', 
            array( 'jquery' ), 
            '1.0', 
            true 
        );
    }
    ```

This will ensure that jQuery is loaded before your script is loaded, and uses the
version included with WordPress.

Because the copy of jQuery included in WordPress loads in [noConflict()](https://api.jquery.com/jQuery.noConflict/)
mode, you should also wrap your code in an Immediately Invoked Function Expression,
or IIFE.

    ```javascript
    ( function( $ ) {
        // Your jQuery code goes here
    } )( jQuery );
    ```

This prevents the use of the `$` variable by other JavaScript libraries from conflicting
with your jQuery code.

## Further reading

For these, and other JavaScript best practices when developing themes, make sure
to read the [JavaScript Best Practices Handbook](https://developer.wordpress.org/themes/advanced-topics/javascript-best-practices)
page under the Advanced Topics section of the WordPress Developer Handbook.

 This is a preview lesson

Register or sign in to take this lesson.

 [ Take course ](https://learn.wordpress.org/course/intermediate-theme-developer/)

 [ Sign in ](https://login.wordpress.org/?redirect_to=https%3A%2F%2Flearn.wordpress.org%2Flesson%2Fjavascript-in-themes%2F&locale=en_US)

##  Suggestions

 Found a typo, grammar error or outdated screenshot? [Contact us](https://learn.wordpress.org/report-content-feedback/).