2

I'm trying to use the has_shortcode() function to only load certain scripts when there is a shortcode in the post's content, with this code:

wp_register_script( 'shortcode-js-file' , FILE_URI, array( 'jquery'), '', true );

if(isset($post->post_content) && has_shortcode($post->post_content, 'shortcode_name')) {
  wp_enqueue_script( 'shortcode-js-file');
}

So in the above code, I'm registering the script on all pages, whether there is that shortcode in the post or not, and if there is that shortcode, then I'm enqueuing the script for it.

What I want to know is whether I should put the wp_register_script inside the if statement or not. If it is not too resource intensive then I would rather leave it outside, as I want to put all the wp_register_script code together in one function.

PS. To showcase my problem clearly, I didn't add the hook and functions that I'm using, as it's not important for what I want to inquire.

1 Answer 1

1

wp_register_script() just adds an entry to an array, it doesn’t do anything resource intensive. See WP_Dependencies::add().

Registering scripts early helps to avoid collisions, so you should do that always on wp_loaded.

2
  • Thanks for helping me out. However, isn't it always best to use the wp_enqueue_scripts hook for registering and enqueing scripts? Jul 1, 2014 at 18:35
  • @user1981248 No, use both separate functions on both separate actions. This is why there are two functions, not just one.
    – fuxia
    Jul 1, 2014 at 18:57

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.