Is it better to encapsulate functionality in a jQuery plugin or in a JavaScript function in vanilla?

Let's say I have some bit of JavaScript that will modify the DOM, perhaps hide / show the form field or something like that, and let me assume that I want to complete this task on several pages, but only once or twice on page.

Is it better to encapsulate this functionality in a jQuery plugin or vanilla JavaScript function?

Essentially, these are:

jQuery.fn.toggleFormInput = function() { // Stunning JavaScript/jQuery magic here } 

better or worse than this:

 function toggleFormInput () { // Stunning JavaScript/jQuery magic here } 
+8
javascript jquery jquery-plugins
source share
2 answers

It depends on the rest of your site. If you use the rest of the jQuery library, then you can use the specific jQuery functions inside your own - each () is a good example. This kind of jQuery magic can allow you to write less code. I would look at some benchmark in which you write both, and see which one is faster.

But if you need a feature that you can move from site to site without dependencies, it might be a good idea to go alone with Javascript. Personally, I would be inclined to use simple Javascript so that I would not be associated with any library, but with your choice.

+2
source share

Well, when I do such things, I use the usual javascript functions, I think it is easier to look for such a function, I see no flaws with pure javascript, and I see one flaw with jQuery.fn, that is, when someone looks at your code and sees $("selector").someFunctionName , it may try to find jquery docs for this function.

+1
source share

All Articles