Best Practices for Seperating jQuery from HTML/PHP

I am creating several jQuery scripts to help validate forms before they are submitted. I have read that it is best to always separate jQuery scripts into a separate file so that you can load the script with wp_enqeue_script.

However, if I am doing something like this:

Read More
jQuery(function()
{
    var ButtonSelector = "#submit-button";

    jQuery(document).on('click', ButtonSelector, function()
    {
        var ValidEntry = true;

        ClearError('#venue_name');
        var name = jQuery("#venue_name").val();
        if (name == "")
        {
            CreateError("#venue_name", "Name is Required");
            ValidEntry = false;
        }

        if (!ValidEntry)
        {
            jQuery('html, body').animate({scrollTop:0}, 'slow');
        }

        EnableButton(ButtonSelector);
        return false;
    });
});

Since this function is only used in the one individual form, would it still make sense to separate it out? If I did separate it, wouldn’t that mean that it would load for every single page?

Related posts

3 comments

  1. You can target a specific page using is_page() when you are enqueueing your JS file.

    function my_scripts_method() {
        if( is_page('your page title') ){
          wp_enqueue_script( 'your-js-script' );
        }
    }
    
    add_action( 'wp_enqueue_scripts', 'my_scripts_method' ); 
    

    This way, you will conditionally enqueue your JS to that page only.

  2. you could still put the script in a seperate js-file, but separate from the rest of your script(-files) too – and enqueue it conditionally, for example:

    if (is_page_template('abc-xyz.php')) {
        wp_enqueue_script('your_script-js', get_template_directory_uri() . '/inc/js/your_script.js', array('jquery'), '1.00', true);
    }
    

    that would be in your functions.php, where you enqueue your scripts

  3. When using is_page() I would also recommend doing so with an || since the page title and page name (aka page slug) might change – if only by accident. You could also use the page ID but that too might not be consistent between development and production.

    For example:

    if ( is_page( $name ) || is_page( $id ) || is_page( $title ) ) {}
    

    Overkill? Perhaps. But it’s something to be aware of.

Comments are closed.