开发者

Attaching a jQuery plugin on-the-fly for better performance

开发者 https://www.devze.com 2023-04-09 20:29 出处:网络
Recently I needed to attach a large number of a jQuery color picker plugin on a page. With color inputs for borders, shades, gradients, and so on, that quickly became a lot of color pickes. Since the

Recently I needed to attach a large number of a jQuery color picker plugin on a page. With color inputs for borders, shades, gradients, and so on, that quickly became a lot of color pickes. Since the tool was loaded repeatedly for 50+ elements, the page would instantiate 500+ color pickers. Needless to say, the browser suffered big time.

So first, I spend some time trying out different methods for having all the inputs share a single instance of the color picker. It seems to me that that would be the soundest way of doing it. But the project situation didn't allow me to spend enough time for finding a way of doing that, so I had to come up with an alt开发者_StackOverflow中文版ernative technique.

I did, and I would like to hear what you think about the technique I came up with, and if anyone sees any problems with it?

The idea is, that instead of attaching all the instances of the plugin when the page loads, you wait, and attach just the instances you need – just when you need them.

Here is how I implemented that.

First I had some html with lots and lots of inputs like this one:

<input class="color">

Then, to assign the jQuery color picker plugin to these inputs, I'd normally do something like this:

jQuery(function($) {
    $('input.color').myColorPicker();
});

But that would result in a number of color picker objects being instantiated right away, one for each matched element, each ready to do its stuff when its input is clicked. This normally works fine, but if there are lots of elements, it can make the browser unresponsive.

So instead, here's how I now attach a color picker to an input on-the-fly if the user actually click on it.

jQuery(function($) {

/* Color pickers*/
$('input.color').live('focus', function(event){

// attach a colorpicker on an as needed basis,
// and only if it is not already attached
if(!$(this).hasClass('haspicker')){
    $(this).myColorPicker().addClass('haspicker');
}

});

When The page loads no color pickers are attached. When the user clicks an input field with the 'color' class, it first receives focus, and the picker plugin gets attached, and the element gets an ectra class that is used to prevent subsequent double binding, then the click event fires and triggers the color picker to show up.

It works fine, but I'm not sure if it's a good practice, or if there could be potential problems with this approach that I haven't thought of.

So I'd just like to hear what you think?


Sounds reasonable. Another try would be to have just one picker instance onload, and then attach it to the element in focus (I assume the user never needs two parallel pickers).

0

精彩评论

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