4 ms·
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 d
by yahelc 14y ago
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.
- exogen 14y agoFor 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.
- zachrose 14y agoMy understanding is that modifying and querying DOM elements is what's slow, not just creating them. http://jsperf.com/lazy-url-parsing http://jsperf.com/lazy-url-parsing
- exogen 14y agoI'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.
- yahelc 14y agoAdded a test case for not caching the DOM element: http://jsperf.com/lazy-url-parsing/2 http://jsperf.com/lazy-url-parsing/2
- yahelc 14y agoClever! Didn't realize you could reuse the element.