Skip to content

Instantly share code, notes, and snippets.

@darkliquid
Last active August 22, 2019 02:28
Show Gist options
  • Save darkliquid/5244870 to your computer and use it in GitHub Desktop.
Save darkliquid/5244870 to your computer and use it in GitHub Desktop.
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");
}());
@Relequestual
Copy link

YAY

@darkliquid
Copy link
Author

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

@jsit
Copy link

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