Enqueue a Script -WordPress

wp enqueue scripts

wp enqueue scripts

WordPress has an enqueuing system for adding local/remote scripts along with styles to prevent conflicts with plug-ins. Since most users run WordPress with a theme and several plugins, developers are advised to use the correct method of loading scripts into WordPress.

Descriptions

wp_enqueue_scripts is the proper hook to use when enqueuing items that are meant to appear on the front end. Despite the name, it is used for enqueuing both scripts and styles.

Example

Enqueue a script – Code Details

Descriptions

Registers the script if $src provided (does NOT overwrite), and enqueues it.

Parameters

$handle
(string) (Required) Name of the script. Should be unique.
$src
(string) (Optional) Full URL of the script, or path of the script relative to the WordPress root directory.
Default value: ”
$deps
(array) (Optional) An array of registered script handles this script depends on.
Default value: array()
$ver
(string|bool|null) (Optional) String specifying script version number, if it has one, which is added to the URL as a query string for cache busting purposes. If version is set to false, a version number is automatically added equal to current installed WordPress version. If set to null, no version is added.
Default value: false
$in_footer
(bool) (Optional) Whether to enqueue the script before instead of in the . Default ‘false’.
Default value: false

The Mistake

WordPress have a wp_head function that allows you to load anything in the head section of the site. For those who don’t know better, they simply add their scripts by using a code like this:

While the above code is an easy way, it is the wrong way of adding scripts in WordPress. For example, if you load jQuery manually and another plugin that also uses jQuery loads it through the proper way, then you have jQuery being loaded twice. It is also possible that the two are different versions which can also cause conflicts

You may also like

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *