On the fly rendering [JS hack]
Today I did a really cool JavaScript hack which I want to share.
The issueSometimes you render something that's complex. Todoist has a view all query which displays all projects and their items. The issue is, that view all is quite computing expensive if an user has lots of items (the query can take some seconds to render). The solutionTo provide "live rendering" our trick is to render one project at a time using window.setTimeout. window.setTimeout executes a function (or some code) after a certain delay. The code we are going to optimize looks like this: AJS.map(projects, function(project) {
renderProject(project);
});
We create a new helper function called projectDispose: function projectDispose(projects) {
renderProject(projects.shift());
if(list.length > 0)
window.setTimeout(AJS.partial(projectDispose, list), 10);
}
Now we just replace the loop, with a function call: projectDispose(projects);
And bam, this forces the browser to render on the fly! The generic solutionOne can solve this generically: function forceLiveRendering(fn, list) {
fn(list.shift());
if(list.length > 0)
window.setTimeout(AJS.partial(forceLiveRendering, fn, list), 10);
}
Anytime you want live rendering of something, you just use forceLiveRendering, e.g.: forceLiveRendering(projectDispose, projects);
Code
·
Code improvement
·
JavaScript
·
Tips
•
17. May 2007
|
|