ThemeShaper Forums » Thematic

[closed]

Load javascript only on specific page

(4 posts)
  • Started 3 years ago by Thompson
  • Latest reply from Thompson
  • This topic is resolved
  1. Thompson
    Member

    Hi all, Does anybody know how to load JS only on a specific page?

    function childtheme_deregister_script() {
    wp_deregister_script( 'pluginJS' );
    wp_register_script( 'pluginJS', ("http://www.domain.com/wp-content/themes/thematic-child/form.js"), false);
    if ( is_home() ) {
    wp_enqueue_script( 'pluginJS' );
    }
    }
    add_action( 'wp_print_scripts', 'childtheme_deregister_script', 100 );

    This works to the extent that it removes the plugin's original javascript ('pluginJS') and instead loads mine from the URL. But it still does not load on only the specified pages. Any help please?

    Posted 3 years ago #
  2. I'm not 100%, but I've seen a few times where if things don't fire on specified pages, it's (based on something I learned from Gene) because your script isn't being called early enough in Wordpress's order of operation. Try swapping 'wp_print_scripts' with 'template_redirect'.
    As this is the point when wordpress makes the decision as to what page to load, this may be the right place to stick a page-specific script like this.

    Posted 3 years ago #
  3. Thompson
    Member

    Thank you tarpontech. template_redirect seems to work too. I saved that trick in case I need it in the future. It turns out that I think the problem with my code was that the if statement needs to be on the wp_register_script that specifies the URL of the new script. And since wp_enqueue_script can be in place of wp_register_script (at least from my reading), I ended up using just enqueue to try to keep it as short as possible. So this is what I ended up with:

    // Remove plugin JS and add my JS only where needed
    function childtheme_deregister_script() {
    wp_deregister_script( 'pluginJS' );
    if ( is_single('26') ) {
    wp_enqueue_script( 'pluginJS', ("/wp-content/themes/thematic-child/form.js"), false,'1.0');
    }
    }
    add_action( 'wp_print_scripts', 'childtheme_deregister_script', 100 );

    Thanks.

    Posted 3 years ago #
  4. Thompson
    Member

    Whoa, I just found a really cool conditional tag in the codex, in case anyone is interested:

    comments_open()

    So you can actually set up WordPress to only load WordPress' commenting javascript if comments are open on a particular post or page. Now that is pretty cool. http://codex.wordpress.org/Conditional_Tags#Any_Page_Containing_Posts

    Posted 3 years ago #

RSS feed for this topic

Topic Closed

This topic has been closed to new replies.