Created
January 8, 2020 13:27
-
-
Save MarinX/837f75d94bab56017206ac566b69a111 to your computer and use it in GitHub Desktop.
Shopify Reading Time Tracker - push GA events for articles
This file contains hidden or 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
| {% if article %} | |
| <script type="text/javascript"> | |
| (function () { | |
| var articleName = "{{article.title}}"; | |
| //IMPORTANT! Change this to the class name of the div article content | |
| var articleContent = "blog__article__content"; | |
| //IMPORTANT! | |
| init(); | |
| function init() { | |
| if (typeof gtag === 'function') { | |
| var content = document.getElementsByClassName(articleContent); | |
| if (content.length <= 0) { | |
| console.error("No content found for class name " + articleContent); | |
| return; | |
| } | |
| content = content[0].innerText.trim(); | |
| var time = readingTime(content); | |
| if (time <= 0) { | |
| console.error("Reading time is 0! Seems like no content or wrong class name"); | |
| return; | |
| } | |
| console.log(time); | |
| setTimeout(gTrack, time); | |
| } else { | |
| console.log('Not loaded'); | |
| setTimeout(init, 500); | |
| } | |
| } | |
| function ansiWordBound(c) { | |
| return ( | |
| (' ' === c) || | |
| ('\n' === c) || | |
| ('\r' === c) || | |
| ('\t' === c) | |
| ) | |
| } | |
| function readingTime(text, options) { | |
| var words = 0, start = 0, end = text.length - 1, wordBound, i | |
| options = options || {} | |
| // use default values if necessary | |
| options.wordsPerMinute = options.wordsPerMinute || 200 | |
| // use provided function if available | |
| wordBound = options.wordBound || ansiWordBound | |
| // fetch bounds | |
| while (wordBound(text[start])) start++ | |
| while (wordBound(text[end])) end-- | |
| // calculate the number of words | |
| for (i = start; i <= end;) { | |
| for (; i <= end && !wordBound(text[i]); i++) ; | |
| words++ | |
| for (; i <= end && wordBound(text[i]); i++) ; | |
| } | |
| var minutes = words / options.wordsPerMinute; | |
| return minutes * 60 * 1000; | |
| } | |
| function gTrack() { | |
| gtag('event', 'read', { | |
| 'event_category': 'Article', | |
| 'event_label': articleName | |
| }); | |
| } | |
| }()); | |
| </script> | |
| {% endif %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment