Thursday, August 13, 2015

life without jQuery

I've finally turned my attention back to my lowLag low latency HTML5 audio project... I've been neglecting it for far too long, especially considering it's the strongest example of a successful opensource project in my portfolio.

One upgrade is getting rid of the dependency on jQuery. (Especially since I plan to be doing a lot of work in processing.js, and need both libraries seems silly.)

You Might Not Need jQuery is a tremendously useful page for this, showing the vanilla-javascript version of jQuery phrases, but it favors conciseness over completeness.

The biggest difference living without jQuery's tremendous merge of CSS-style selectors with general attribute and style wrangling is living without jQuery's implicity "foreach"; you can do an operation against a selector that matches zero, one, or many objects, and jQuery will do what you expect. In pure Javascript land, however, the zero case can be prone to null errors if one isn't careful, and any loop you have to build yourself.

For my lowLag object, I found it useful to add the following convenience functions:
this.createElement = function(elemType,attribs){
var elem = document.createElement(elemType);
if(attribs){
for(var key in attribs){
elem.setAttribute(key,attribs[key]);
}
}
return elem;
};
this.safelyRemoveElement = function(elem){
if(elem) elem.parentNode.removeChild(elem);
};
this.safelyRemoveElementById = function(id){
this.safelyRemoveElement(document.getElementById(id));
};

So I replaced code like
$(body).append("<div id='lowLag'></div>");
with the somewhat clunkier
var divLowLag = this.createElement("div",{"id":"lowLag"});
document.body.appendChild(divLowLag);

safelyRemoveElement points out how jQuery's $("some selector").remove(); covers up how you really are modifying the parent of an element when deleting the child.



No comments:

Post a Comment