Codementor Events

Introduction to Monkey Patching jQuery

Published May 11, 2019Last updated Apr 03, 2020
Introduction to Monkey Patching jQuery

In this article I will show you how to modify jQuery using a technique called "Monkey Patching 🐡" or "Duck Punching πŸ¦†". Don't worry, there is no animal cruelty involved πŸ˜ƒ

This is a common technique in dynamic languages like JavaScript, Python, Ruby for replacing the behavior of a program during runtime.

According to Wikipedia:

A monkey patch is a way for a program to extend or modify supporting system software locally (affecting only the running instance of the program).
Full article

Confused? Let's look an example to make it simple πŸ’‘.

Basic Example ✨

Let's look at a basic jQuery function. In this case our function sets text of the given element to "Hello, World!".

Here is our HTML code.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="js/jquery.js"></script>
  <script src="js/patch.js"></script>
  <title>Document</title>
</head>
<body>    
  <div id="message"></div>
  <input type="button" id="button1" value="Do It!">
</body>
</html>

and JavaScript

$(document).ready(function() {
  $.fn.hello = function() {
    this.text('Hello, World!');
  };
  $('#button1').click(function() {
    $('#message').hello();
  });      
});

Output
code1.png
Now, let's write a patch that will append something to the existing text. So, basically our patch will append text to the original "Hello, World!".

Here is our patched version of the code. It is written as an IIFE (Immediately Invoked Function Expression).

πŸ“ Note: You can find more details abolut IIFE here.

$(document).ready(function() {
  $.fn.hello = function() {
    this.text('Hello, World!');
  };
  $('#button1').click(function() {
    $('#message').hello();
  });      
  (function($) {
    var original = $.fn.hello;
    $.fn.hello = function() {
      original.apply(this, arguments);
      if(this.text() === 'Hello, World!') {
        this.append(' and Hello, Monkey Patching!');
      }
    }
  }(jQuery));
});

Output
code2.png
So, now we undertand the basics. Let's look at a real world example. Let's modify jQuery using a monkey patch.

Modifying jQuery πŸ’²

Let's modify jQuery itself and see how it will give us different output. I am going to show how we can patch $.now() to get more friendly date and time value. The default implementation returns a number by calling (new Date).getTime().

  (function($) {
    var orig = $.now;
    $.now = function() {
      return new Date().toLocaleString();
    }
  }(jQuery))

Output
code3.png
There it is βœ…

We have successfully patched jQuery and now we are getting a more user friendly date/time value from $.now(). We can use same technique to patch other jQuery functions and plugins.

Final words πŸ“

Monkey patching has several advantages in certain situations, and it can be very beneficial if done with care and attention.

Benefits:

  • You can write a patch to fix a problem until it is fixed in official jQuery release.
  • You can modify functionality without modifying actual jQuery code
  • It is easy to remove it, because you are not modifying source code of jQuery, you can just delete the patch file to remove it.

Pitfalls:

  • It can break functionality due to conflict with existing variable or function.
  • If multiple patches are trying to modify a function the last executed patch is applied.
  • The patch can stop working if there are breaking changes in newer version of jQuery.

I hope this was helpful. Please write in comments if you have any questions or suggestions. I will try to get back to you on earliest. πŸ‘

giphy.gif

Discover and read more posts from Humayun Shabbir
get started
post commentsBe the first to share your opinion
Show more replies