How resource intensive is wp_register_script()?

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

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.

Leave a Comment