Last active
August 22, 2019 02:28
-
-
Save darkliquid/5244870 to your computer and use it in GitHub Desktop.
Bookmarklet to estimate reading time of a page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | |
}()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")}()); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
}()); |
Dodgy benchmark comparing the recursive against the non-recursive here: http://jsfiddle.net/HDeT2/1/
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
YAY