Load Custom JavaScript Like a Pro in your WordPress plugin

  • Home / Load Custom JavaScript Like a Pro in your WordPress plugin

Load Custom JavaScript Like a Pro in your WordPress plugin

If you are a WordPress developer then a challenge that you are possibly facing sooner or later that how to include custom JavaScript files effectively in your WordPress plugin. Well, there are various ways to do that. But what is the best way ? In this tutorial, I’ll discuss it and show the best way to doing that. Keep reading.

Suppose you have developed a custom plugin and the plugin adds a custom shortcode. The shortcode needs some JavaScripts and jQuery is the necessary dependency.  If you are just a newbie WordPress developer and during your development you might be excited (!) to write something like this in your plugin file :


It’s perfectly OK, but let’s see the drawbacks.

  1. Since the WordPress 2.6 , the user can move the WordPress directory anywhere he wants. It means instant plugin break.
  2. If the user another plugin that also load jQuery as a dependency, the page then end up loading jQuery loaded twice . Which is a very bad practice.

We can improve it.

What the script actually does??

  1. It always get the correct URL for loading the files.
  2. Before it loads, it checks JQuery is correctly included or not.

That’s a better implementation. But what about your shortcode appears on a single page ??

The trouble with the wp_enqueue_script() is that you must have to call it before the wp_head() hook. For a single page, before the page is rendered, you need to decide you should add the script or not.

We still have rooms for better way to load files.

What does it do ?

  1. The script will be loaded only if my_script global variable was set at some point during the page load.
  2. You are calling wp_enqueue_scripts () directly, instead of relying on WordPress.
  3. It will still check if jQuery was added or not.

Now you can set $my_script flag from any function or method. Including your shortcode like that:

So the script will be added only if [‘my-shortcode’] was found in any post of the current page or any single page.

This method is also called lazy loading. Means the required files and dependency will be loaded only when they are called or required.

Note: You can visit our main site for Outsource your WordPress Development Projects.

Leave Comments

Contact Us