When I came to know the function wp_register_script(), I had some questions came to my mind:
Should I register each script first and then enqueue it? And is this a best practice?
Or, Should I normally not register each script?
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It only takes a minute to sign up.Sign up to join this community
I have gone through some articles and come to the following conclusion. I think it helps.
wp_register_script()is just registering; not loading it. The registered script will not be loaded until it is enqueued using
wp_enqueue_script()function automatically registers the script.
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
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_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