Skip to content

Instantly share code, notes, and snippets.

@darkliquid

darkliquid/beautified.js

Last active Aug 22, 2019
Embed
What would you like to do?
Bookmarklet to estimate reading time of a page
javascript:(function () {
function getTextNodesIn(element) {
var wordcount = 0,
whitespace = /^\s*$/;
function getTextNode(node) {
// type 3 is a textnode
if (node.nodeType == 3) {
// We skip text nodes that are only whitespace
if (!whitespace.test(node.nodeValue)) {
wordcount += node.nodeValue.split(" ").length;
}
// this isn't a text node, so test each childnode
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
getTextNode(node.childNodes[i]);
}
}
}
getTextNode(element);
return wordcount;
}
alert("Estimated reading time: " + (getTextNodesIn(document.body) / 250) + " minutes")
}());
javascript:(function(){function getTextNodesIn(c){var d=0,b=/^\s*$/;function a(g){if(g.nodeType==3){if(!b.test(g.nodeValue)){d+=g.nodeValue.split(" ").length}}else{for(var f=0,e=g.childNodes.length;f<e;++f){a(g.childNodes[f])}}}a(c);return d}alert("Estimated reading time: "+(getTextNodesIn(document.body)/250)+" minutes")}());
javascript:(function () {
function getTextNodesIn(element) {
var wordcount = 0,
whitespace = /^\s*$/,
nodelist = [element];
while (nodelist.length > 0) {
var node = nodelist.pop();
if (node.nodeType == 3) {
// We skip text nodes that are only whitespace
if (!whitespace.test(node.nodeValue)) {
wordcount += node.nodeValue.split(" ").length;
}
// this isn't a text node, so test each childnode
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
nodelist.push(node.childNodes[i]);
}
}
}
return wordcount;
}
alert("Estimated reading time: " + (getTextNodesIn(document.body) / 250) + " minutes");
}());
@darkliquid

This comment has been minimized.

Copy link
Owner Author

@darkliquid darkliquid commented Mar 26, 2013

Finds all text nodes, splits them into words, counts total words across them, divides by 250 (between 200 and 250 wpm is the average adult reading speed)

@Relequestual

This comment has been minimized.

Copy link

@Relequestual Relequestual commented Mar 26, 2013

YAY

@darkliquid

This comment has been minimized.

Copy link
Owner Author

@darkliquid darkliquid commented Mar 27, 2013

Dodgy benchmark comparing the recursive against the non-recursive here: http://jsfiddle.net/HDeT2/1/

@jsit

This comment has been minimized.

Copy link

@jsit jsit commented Feb 26, 2014

Thanks for this -- mind if I use this code in another project to be put on GitHub?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.