Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This is a great trick, but there's an irritating IE bug. On the pathname attribute, IE doesn't add a leading slash on the pathname (whereas all other browsers do).

It can be corrected by doing:

    parser.pathname = parser.pathname.replace(/(^\/?)/,"/");
Further, because you're creating a DOM element, it's less performant than using a RegExp solution. That performance degradation will typically only surface if you're parsing a large number of URLs (for example, in a loop), rather than just 1 or 2.


For the DOM element, it seems like you could just create the element once and then keep it around for reuse. Should be safe since JavaScript is single-threaded.


My understanding is that modifying and querying DOM elements is what's slow, not just creating them.

http://jsperf.com/lazy-url-parsing


Added a test case for not caching the DOM element: http://jsperf.com/lazy-url-parsing/2


I'm actually surprised it's only ~40% slower (in my Chrome anyway). Considering how much less code it is to maintain, that's totally worth it IMO. I'm sure there are a thousand other functions you'd want to optimize in a real app before this.


Clever! Didn't realize you could reuse the element.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: