When I came to know the function wp_register_script(), I had some questions came to my mind:

  1. Should I register each script first and then enqueue it? And is this a best practice?

  2. Or, Should I normally not register each script?


I have gone through some articles and come to the following conclusion. I think it helps.

  1. Registering any scripts using wp_register_script() is just registering; not loading it. The registered script will not be loaded until it is enqueued using wp_enqueue_script().
  2. We don’t need to register and enqueue each of the scripts simultaneously. We should just enqueue. Registering is not mandatory as the wp_enqueue_script() function automatically registers the script.
  3. But we do need to register while we are in any of the following situations:

a. Suppose we need a script to load into more than one place like once in front-end and once in back-end (admin page). Now we can register the script just once. And then enqueue it in front-end and back-end individually. Look, enqueueing means loading. Registering doesn’t mean loading. In case we don’t register it, it will be automatically registered as many times as we enqueue it. On the other hand, if we register it once, it will be registered once, no matter how many times we enqueue it.

b. If we want to use a script as a dependency of other scripts, then we don’t need to enqueue it with wp_enqueue_script(). Just register it with wp_register_script(). And it will be automatically enqueued when we use it’s handle name as a dependency of other scripts enqueued with wp_enqueue_script().

c. If we want the script to be loaded when necessary rather than to be loaded at once, we can just register it for later use. The use case has been shown above. N.B. As far as I am convinced, the same conclusion can be drawn for the CSS stylesheets. I mean to say that we can use wp_register_style() and wp_enqueue_style() in the same way. Note that the conclusion drawn here reflects my own deduction. If I’m wrong, please correct me.

for more details: https://sxbook.blogspot.com/2018/12/wpregisterscript-when-to-use.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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