wordpress essential plugins

HowTo Conditionally de-register JS, CSS scripts in WordPress to avoid Dependency Pollution

WordPress is a very popular platform, as you may know already, counting hundreds of thousands of themes and plugins cause of its developer-friendly approach. So, plugins, may have a GUI. User interfaces in web development, as we know it, need css and js for their graphics and functionalities etc.

WordPress core dev team brought us, a long time ago, functions that help us (developers) to register and enqueue css and js dependencies into WordPress CMS. Of course when we build stuff around WordPress we don’t use one plugin. We tend to use a dozens of them!

Imagine all these plugins, enqueuing jquery plugins, js libraries, css frameworks … Some depend on the same code libraries, which are included globally.

But what happens if we use the same library, and for some reason, include a different version?

We globally include multiple versions (deprecated or not) of the same javascript libraries. This is a relatively new kind of pollution in WordPress. We’ll call it dependency pollution from now on.

Note: Dependency pollution should not be confused with Namespace Pollution. If you need to read more about namespace pollution you can read Chris Quick article.

 

The Solution

Just as every problem has its solution, Dependency Pollution can be solved by adopting the right habits when writing code and replacing the old rusty ones.

Just don’t include your scripts globally! Include them where you Actually need them!

Use hook suffixes to determine if the current page belongs to your plugin and then; Include your scripts safely.

 

How to do it conditionally

From the WordPress Plugin Development Handbook we see how to use actions. The action to use to enqueue scripts is admin_enqueue_scripts; Which eventually will kindly return one argument back to your function.

The hook suffix! Namely: the current admin page!

 

First Aid: Solve the conflict

If you find yourself in such position, don’t hesitate; drop an informational and kind tweet to the developer of the conflicting plugin like this one:

 

Well, after doing so and in order to continue with your life, and, to actually solve the problem, you can Use wp_deregister_script( string $handle ) to de-register scripts that conflicts with yours. But do it conditionally too. Good habits, remember?

 

References:

do_action( 'admin_enqueue_scripts', string $hook_suffix )

add_action( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )

What we’ve learned today:

Enqueue scripts conditionally!
De-Register scripts conditionally!

Resolution: Green Thinking Developers are much better developers than the others!

Comment:

This site uses Akismet to reduce spam. Learn how your comment data is processed.