Custom tumblr 404 error page

I wanted to have a custom 404 page for a client project, but tumblr does not have the ability to define a custom style or even custom content for the 404 error page. There are some ways around this, but solutions like that have the problem that they do not really always work because they look for a certain error text in the page, but that error text is actually translated according to a visitor’s language preference (as set in their browser). The solution I came up with is to do an AJAX HTTP HEAD request via jQuery to the current document URL, and if that returns a 404 status code, forward to the custom 404 page (which is an actual custom page on the tumblr blog in question—you could also replace or alter the page content via JavaScript instead if you were so inclined). Here’s the code:

// Make a request to ourself to figure out if this returns a 404,
// and if that is the case, show our custom 404 page
$.ajax(document.location.href, {type: 'HEAD'}).fail(function (jqXHR, textStatus, errorThrown) {
	if (jqXHR.status == 404)
		location.href = document.location.protocol + '//' + document.domain + '/not-found';
});

This still has the problem that it will briefly show the error page in the blog’s normal layout before the redirection occurs, also if the user navigates back they will end up being redirected again (this could be solved by using location.replace).

Here you can see the solution in action.