A couple of days ago David Walsh posted a blog entry where he recommended a video from Google about JavaScript. I’ve found this very interesting and I have done some research about how to implement this very easy to Mootools. There are a lot of do’s and dont’s but what is the best practice for us as a Mootools developer? How to avoid the basic Mootools solutions and speed up your plugins? Well, I’ll post my neat workarounds to get your speed up.
I’ll start with modifying the DOM by injecting elements with the Mootools function inject(). Injecting elements to the DOM is very common with Mootools but it will make it slow down. To speed up you’ll have to do as little DOM modification as possible.
For example you load a JSON file and add elements depending on the content of the request. In this example we don’t avoid the Mootools each() function. We focus on the point that we don’t call the inject() function every time. This is my solution.Add the following lines to you general JavaScript file to implement a new function. I’ll recommend this if you
view plaincopy to clipboardprint?
window.addEvent('domready', function() {
Element.implement({
docFragment: function(){
return document.createDocumentFragment();
}
});
});
We’re going to add options to a select element, based on the JSON request.
view plaincopy to clipboardprint?
var fragment = Element.docFragment();
json.each(function(o){
var option = new Element('option',{'value': o.value, 'html': o.html});
fragment.appendChild(option); //No reflow
});
$('select').appendChild(fragment); //Reflow!
Results
I’ve done some testing and I think it helped me pretty good to speed up my scripts. I’ve modified my cvLinkSelect class and did some testing with it. Here are the results. Not very impressive at this point but you can see it will help the performance.
The test handles a 12 lined JSON request and for each record an option element will be added to the DOM. Not a very big effort for a browser, but you’ll see that there is some difference on the most common browsers and it’s no surprise that IE is the slowest of them all. If you scale this up it has to be a large difference and I’m confident with that.
Read more about createDocumentFragment on Mozilla Developer Center.
reference : http://youngdutchdesign.com/speeding-up-mootools-with-createdocumentfragment
2011年11月29日 星期二
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言