How to Use wp_enqueue_script to Load JavaScript in WordPress

During the inception of Internet, there were just basic bland pages made of tables without any interactivity or creativity. With HTML and CSS being the primary blocks for building layouts in websites, there was no scope for imodern-day nteractivity and flexibility. But with advent of JavaScript, everything changed. With JavaScript we could do everything that we could imagine.To say JavaScript revolutionized the Internet wouldn’t be a stretch. JS opened doors to infinite possibilities and shaped Internet as we know it today. Websites created using WordPress can also utilize the power of JavaScript and other JavaScript based libraries to enhance user experience create modern websites. In this article, we look in detail at how to add JavaScript in WordPress using wp_enqueue_script hook offered by WordPress.

Before going into the workings of wp_enqueue_script action hook, we will learn more about JavaScript and how it is shaping the internet today.

What is JavaScript?

As per MDN docs, “JavaScript is a scripting or programming language that allows you to implement complex features on web pages — every time a web page does more than just sit there and display static information for you to look at — displaying timely content updates, interactive maps, animated 2D/3D graphics, scrolling video jukeboxes, etc. — you can bet that JavaScript is probably involved.” JavaScript is basically what makes webpages come to life. Some of the things that JavaScript can achieve include –

1. Interact with Elements in response to events

We can perform actions based on events on a webpage. Changing color on clicking, fading in/out of elements, creating popups, scroll based events are some of the instances of event based animations. The DOM API offered by JavaScript is responsible for any DOM based action or event.

2. Smooth 2D and 3D Animations

JavaScript is capable of creating smooth animations and visual effects to liven up your webpages. JavaScript offers many libraries such as anime.js, three.js and many more to help create amazing animations.

3. Fetch your location

You must have heard of Google Maps. Well, it uses… that’s right… JavaScript! JavaScript offers a GeoLocation API using which we can get location and show in the browser.

4. Handle Multimedia and other files

JavaScript allows you to handle Audio and Video files with relative ease. You can integrate any media format easily in your website and do many interesting things with it. You can even create your own media player with JavaScript. Apart from media, you can integrate PDFs, doc files, Images and many other formats in your website using JavaScript.If you are in the market for superclone Replica Rolex , Super Clone Rolex is the place to go! The largest collection of fake Rolex watches online!

and much, much more!

If you ever look at a website and think “how is this happening?”, chances are JavaScript is involved. Earlier, JavaScript was a client-side language which was used in browsers but off-late, JavaScript has expanded its capabilities to offer server-side functionalities as well. Some modern day websites are completely built using JavaScript and its respective libraries.

How to add JavaScript to WordPress with wp_enqueue_script

Now that we’ve been introduced to JavaScript, let’s see how to add JavaScript in WordPress. WordPress utilizes a powerful function wp_enqueue_script to add JS files and resources in WordPress. With this function, we can add JS resources to our themes and plugins. Let’s take a detailed look into this hook. In order to follow along with this article, you might require basic familiarity with WordPress file structure and basic terminology.

For simplicity sake, we consider a standard theme directory with style.css and functions.php files in the root directory, a js folder having main.js file in it.

File Structure

We need to enqueue main.js file in our theme.

First of all, let’s add some code to our main.js file. Add the following code to main.js –

As you can see, it’s a pretty standard alert box saying “Cheers! File is enqueued.”  Now, in order to enqueue this file and make it show up in the browser, we need to add some code to our functions.php file.

After adding these four lines of code, our main.js file gets enqueued and you’ll see the alert box in your browser. Something like this –

Alert Box

Now, let’s go through these few lines that are helping us add JS to our theme. Basically, we are writing a function and hooking it to wp_enqueue_scripts WordPress hook using add_action function. I won’t go in much detail about hook but long story short, you can imagine WordPress Hooks as checkpoints when a WordPress page is loads. Different hooks fire at different times in the course of loading of a webpage.

Most of the times, scripts and styles are enqueued using wp_enqueue_scripts action hook but in some cases, they can even be enqueued using the init hook. You can read more about hooks from official WordPress documentation.

Getting back to our code, in the function, we use wp_enqueue_script function to enqueue our main.js file. This function accepts 5 arguments out of which, the first, $handle is required. Rest of the arguments are optional but recommended. Let’s take a look at them.

1. $handle

This is the unique ID for every resource. It should be unique. WordPress refers to this resource using this ID.

2. $src

The path to the file. If unspecified, the function assumes the file is in the same directory as the PHP file. In case the file is in a different directory, we need to mention it here. This argument also accepts third party URLs to fetch resources from CDNs. It proves quite useful when including font and icon libraries.

3. $deps

The dependency array. In case the resource requires additional resource to load before it, you’ll need to add it in the array. You’ll need to add the resource’s $handle as an item of this array. It’s quite useful when you have added third-party libraries in your theme or plugin and want to make sure that your code will throw an error in case the required library doesn’t load before your code that uses the library. If this argument is unspecified or empty, the files load in order specified in the function.

4. $version

This argument accepts a string. This string acts as the version number of the resource. This string appends to the URL string of the resource and is useful for cache busting purposes. If this argument is false, the current WordPress version is automatically added to the URL. If null, nothing gets added to the URL. The default value is false.

5. $args

This argument specifies where to load the resource. It is useful if you want to optimize the loading of your resource. I unspecified, the resource automatically loads in the <head>. There are a couple of values that can be added here.

$strategy

This accepts the values defer and async. This is used to either defer the loading of resource or load asynchronously. You can read more about it here.

$footer

This specifies whether resource loads in header or footer.  Accepts true or false.

Conclusion

In this article, we went into detail about the wp_enqueue_script function and how it is used to add JavaScript in WordPress. It is one of the most important functions in WordPress and you might encounter it several times in your WordPress development journey.

I hope you learnt something here. Please do check out our blog where we share tips, tricks, “AHA!”s and “Gotcha!”s about WordPress. Do reach out if you have any requirement for website, optimization or anything related to website. See you in the next article.

Leave a Reply

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