开发者

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

Let's say i have some bit of JavaScript which will modify the DOM, perhaps hide/show a f开发者_开发技巧orm field or something like that and let's assume I want to execute this task on multiple pages, but only once or twice per page.

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

Essentially, is this:

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

better or worse than this:

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


It really depends on the rest of your site. If you are using the rest of the jQuery library, if you are then you can utilise jQuery specific functions inside of your own - each() is a good example. That kind of jQuery magic might allow you to write less code. I would look into doing some kind of benchmark where you write both and see which one executes faster.

But if you want a function that you can move from site to site without dependancies it might be a good idea to go it alone with Javascript. Personally I would be inclined to use plain Javascript so that I wasn't bound down to any 1 library, but that's your choice.


Well, when i do this sort of stuff i use ordinary javascript functions, i think its easier to look up function like that, i dont see downsides with pure javascript, and i see one downside with jQuery.fn, that is when someone looks at your code and sees $("selector").someFunctionName, he might try searching jquery docs for that function.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜