0

Here's the situation I'm having. I am developing a site and on the single post pages of the site I am using various social sharing buttons (i.e. Google+, Facebook, LinkedIn, Twitter, etc). I am following the official developer documentation for each of these buttons and most of them require inserting JavaScript before the closing tag.

This is all fine and dandy and I've got it working perfectly. However, my only issue is that since these social icons are ONLY on the single post blog pages I don't want that JavaScript being loaded on other pages as it will only add unnecessary resources to be loaded and I'd like to keep my page speed as fast as possible.

For the life of me I can't figure out how to go about doing this. I thought at first about writing some conditional PHP code that detected if you were on a single post page and if so it loaded the scripts in the footer. However, I realized that I don't think there's a realistic way to do that since each single post URL doesn't have a consistent part of the URL in it (i.e. /blog/).

I could add the JavaScripts to the single.php template for single post pages but that wouldn't work either since it's calling the footer in those pages via and I would like these scripts to be loaded in the footer, not the template itself.

Anyways, any input would be appreciated. I'm sure there is a way to do it, I'm just racking my brain and can't figure it out.

1 Answer 1

2
  1. Properly enqueue the scripts, via callback hooked into the appropriate hook
  2. Use contextual conditional tags to determine when to enqueue

For example, you'd do something like:

function wpse135482_enqueue_scripts() {
    // Only enqueue this script on single post pages
    if ( is_singular( 'post' ) ) {
        wp_enqueue_script( $args );
    }
}
add_action( 'wp_enqueue_scripts', 'wpse135482_enqueue_scripts' );

Further reading:

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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