1

I have some JS \ CSS that is used within selected pages on my site for various UI functions, for example an image slider. This image slider is only used on a few pages inside the site and loading it on every request impacts performance.

Is there a best-practice on selectively loading these types of vendor payloads when needed?

function wpdocs_dequeue_script() {
     if( ! is_page('gallery') ) {   
          wp_dequeue_script( 'vendor-slider' );
      }
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );
  • Do i load everything I need in functions.php and then just de-queue what I don't need?
  • Is there a way to configure this from within the page itself, or will this have to be coded into functions.php?

1 Answer 1

1

How are the UI Elements included on the page? If you use a shortcode, you can enqueue the js part (wp_enqueue_script) within the shortcode function. Your JS will then be enqueued in the footer. The CSS would have to be enqueued of course in the header, so you have to enqueue it in the wp_enqueue_scripts action. If you only need it on the pages that have the shortcode, you can do something like this in your wp_enqueue_scripts action function:

add_action('wp_enqueue_scripts','my_awesome_function');

function my_awesome_function(){
  if(is_singular()){
    global $post;
    if(has_shortcode($post->post_content,'my_awesome_shortcode')){
       wp_enqueue_style('my-awesome-style');
    }
  }
}

Happy Coding!

1
  • Its not using a shortcode... Edited my post to show the plugin code loading the scripts.
    – DDulla
    Oct 9, 2019 at 16:44

Your Answer

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

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