This is my solution to loading JavaScript on one page only — for example, a form that requires some validation code. In this case, I’m testing for the existence of a shortcode used to insert my form on the page, but other conditional tests are possible (my RSVPMaker event scheduling plugin tests for $posts->post_type == 'event'
).
The official documentation on the right way to load JavaScript says something about using the ‘init’ action to trigger a wp_enqueue_script function call. The enqueue function prevents multiple copies of the same script from being loaded and also allows you to specify dependencies. However, with ‘init’ you tend to wind out with the script being output on every page whether it’s needed or not. The ‘wp’ action loads just enough later that it’s possible to access the global $post for a WordPress page or single post view, but it still comes before WordPress outputs the page header and scripts.
Then you can do this:
<?php function load_my_js() { if(is_admin() ) return; // never mind if this is an admin page global $post; if(strpos($post->post_content,'[demoform]') == false) return; wp_register_script( 'js_test', plugins_url() . '/demo/test.js', array('jquery') ); wp_enqueue_script('js_test'); } add_action('wp','load_my_js'); ?>
This is loosely based on a post about conditionally loading JavaScript and CSS by Artem Russakovskii. He has a somewhat more complicated function that loops through multiple posts, but I think mine is a little simpler for something like a contact form intended to be used on a separate page.
Is there a reason why this wouldn’t work?