Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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:

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?

share|improve this question
    
All browsers use a cache for that. –  toscho May 28 '13 at 12:20
add comment

3 Answers

up vote 4 down vote accepted

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.