Skip to content

Commit

Permalink
Improved the PV fetching experience.
Browse files Browse the repository at this point in the history
  • Loading branch information
cotes2020 committed Apr 3, 2020
1 parent 0540049 commit 3493bc2
Show file tree
Hide file tree
Showing 9 changed files with 156 additions and 39 deletions.
12 changes: 7 additions & 5 deletions _config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -55,12 +55,14 @@ google_analytics:
# Fill with your Google Analytics ID
id: ''
# The Google Analytics pageviews switch.
# DO NOT enable it unless you know how to deploy the Google Analytics superProxy.
pv: false
# superProxy baseURL and URL, only valid when `google_analytics.pv` is set to 'true'
proxy_baseurl: ''
proxy_url: ''

pv:
# DO NOT enable it unless you know how to deploy the Google Analytics superProxy.
enabled: false
# the next options only valid when `google_analytics.pv` is enabled.
proxy_url: ''
proxy_endpoint: ''
cache: false # pv data local cache, good for the users from GFW area.

disqus:
comments: false # boolean type, the global switch for posts comments.
Expand Down
9 changes: 5 additions & 4 deletions _includes/head.html
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,9 @@
<link rel="preconnect" href="https://www.googletagmanager.com" crossorigin="anonymous">
<link rel="dns-prefetch" href="https://www.googletagmanager.com">

{% if site.google_analytics.proxy_baseurl and site.google_analytics.pv %}
<link rel="preconnect" href="{{ site.google_analytics.proxy_baseurl }}" crossorigin="use-credentials">
<link rel="dns-prefetch" href="{{ site.google_analytics.proxy_baseurl }}">
{% if site.google_analytics.pv.proxy_url and site.google_analytics.pv.enabled %}
<link rel="preconnect" href="{{ site.google_analytics.pv.proxy_url }}" crossorigin="use-credentials">
<link rel="dns-prefetch" href="{{ site.google_analytics.pv.proxy_url }}">
{% endif %}
{% endif %}

Expand Down Expand Up @@ -122,7 +122,8 @@

{% if page.layout == 'home' or page.layout == 'post' %}
<script src="{{ site.baseurl }}/assets/js/dist/timeago.min.js" async></script>
{% if site.google_analytics.pv %}
{% if site.google_analytics.pv.enabled %}
<script src="{{ site.baseurl }}/assets/data/pv-data.json"></script>
<script src="{{ site.baseurl }}/assets/lib/countUp.min.js" async></script>
<script src="{{ site.baseurl }}/assets/js/dist/pageviews.min.js" async></script>
{% endif %}
Expand Down
2 changes: 1 addition & 1 deletion _layouts/home.html
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ <h1>
<i class="unloaded">{{ post.date | date_to_xmlschema }}</i>
</span>
<!-- page views -->
{% if site.google_analytics.pv %}
{% if site.google_analytics.pv.enabled %}
<i class="far fa-eye fa-fw"></i>
<span id="pv_{{-post.title-}}" class="pageviews">
<i class="fas fa-spinner fa-spin fa-fw"></i>
Expand Down
2 changes: 1 addition & 1 deletion _layouts/post.html
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ <h1 data-toc-skip>{{ page.title }}</h1>
</div>

<!-- page views -->
{% if site.google_analytics.pv %}
{% if site.google_analytics.pv.enabled %}
<div>
<span id="pv" class="pageviews"><i class="fas fa-spinner fa-spin fa-fw"></i></span> views
</div>
Expand Down
6 changes: 0 additions & 6 deletions assets/data/proxy.json

This file was deleted.

13 changes: 13 additions & 0 deletions assets/data/pv-data.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
---
layout: compress
---

const proxyData = '{"url": "{{ site.google_analytics.pv.proxy_endpoint }}"}';

{%- capture pv_data -%}
{%- if site.google_analytics.pv.cache and site.google_analytics.pv.enabled -%}
{% include_relative pageviews.json %}
{%- endif -%}
{%- endcapture -%}

const pageviews = '{{ pv_data }}';
1 change: 1 addition & 0 deletions assets/data/search.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
---
layout: compress
---

[
Expand Down
148 changes: 127 additions & 21 deletions assets/js/_src/pageviews.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
*
* Dependences:
* - jQuery
* - countUp.js(https://github.com/inorganik/countUp.js)
* - countUp.js <https://github.com/inorganik/countUp.js>
*
* v2.0
* https://github.com/cotes2020/jekyll-theme-chirpy
Expand Down Expand Up @@ -77,42 +77,148 @@ function displayPageviews(data) {
var path = window.location.pathname;
tacklePV(rows, path, $('#pv'), hasInit);
}

}


var getInitStatus = (function() {
var hasInit = false;
return function() {
if (hasInit) {
return true;
} else {
let ret = hasInit;
if (!hasInit) {
hasInit = true;
return false;
}
return ret;
}
})();


var PvCache = (function() {
const KEY_PV = "pv";
const KEY_CREATION = "pv-created-date";
const KEY_PV_TYPE = "pv-type";

var PvType = {
ORIGIN: "origin",
PROXY: "proxy"
};

function get(key) {
return localStorage.getItem(key);
}

function set(key, val) {
localStorage.setItem(key, val);
}

return {
getData: function() {
return JSON.parse(localStorage.getItem(KEY_PV) );
},
saveOriginCache: function(pv) {
set(KEY_PV, pv);
set(KEY_PV_TYPE, PvType.ORIGIN );
set(KEY_CREATION, new Date().toJSON() );
},
saveProxyCache: function(pv) {
set(KEY_PV, pv);
set(KEY_PV_TYPE, PvType.PROXY );
set(KEY_CREATION, new Date().toJSON() );
},
isOriginCache: function() {
return get(KEY_PV_TYPE) == PvType.ORIGIN;
},
isProxyCache: function() {
return get(KEY_PV_TYPE) == PvType.PROXY;
},
isExpired: function() {
if (PvCache.isOriginCache() ) {
let date = new Date(get(KEY_CREATION));
date.setDate(date.getDate() + 1); // fetch origin-data every day
return Date.now() >= date.getTime();

} else if (PvCache.isProxyCache() ) {
let date = new Date(get(KEY_CREATION) );
date.setHours(date.getHours() + 1); // proxy-data is updated every hour
return Date.now() >= date.getTime();
}
return false;
},
getAllPagevies: function() {
return PvCache.getData().totalsForAllResults["ga:pageviews"];
},
newerThan: function(pv) {
return PvCache.getAllPagevies() > pv.totalsForAllResults["ga:pageviews"];
}
};

})(); // PvCache


function fetchOriginPageviews(pvData) {
if (pvData === undefined) {
return;
}
displayPageviews(pvData);
PvCache.saveOriginCache(JSON.stringify(pvData));
}


function fetchProxyPageviews() {
let proxy = JSON.parse(proxyData); // see file '/assets/data/pv-data.json'
$.ajax({
type: 'GET',
url: proxy.url,
dataType: 'jsonp',
jsonpCallback: "displayPageviews",
success: function(data, textStatus, jqXHR) {
PvCache.saveProxyCache(JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Failed to load pageviews from proxy server: " + errorThrown);
}
});
}


$(function() {
// load pageview if this page has .pageviews

if ($('.pageviews').length > 0) {

// Get data from daily cache.
$.getJSON('/assets/data/pageviews.json', displayPageviews);

$.getJSON('/assets/data/proxy.json', function(meta) {
$.ajax({
type: 'GET',
url: meta.proxyUrl,
dataType: 'jsonp',
jsonpCallback: "displayPageviews",
error: function(jqXHR, textStatus, errorThrown) {
console.log("Failed to load pageviews from proxy server: " + errorThrown);
let originPvData = pageviews ? JSON.parse(pageviews) : undefined;
let cache = PvCache.getData();

if (cache) {
if (PvCache.isExpired()) {
if (PvCache.isProxyCache() ) {
if (originPvData) {
if (PvCache.newerThan(originPvData)) {
displayPageviews(cache);
} else {
fetchOriginPageviews(originPvData);
}
}

fetchProxyPageviews();

} else if (PvCache.isOriginCache() ) {
fetchOriginPageviews(originPvData);
fetchProxyPageviews();
}
});

});
} else { // still valid
displayPageviews(cache);

if (PvCache.isOriginCache() ) {
fetchProxyPageviews();
}

}

} else {
fetchOriginPageviews(originPvData);
fetchProxyPageviews();
}

}

} // endif
});
2 changes: 1 addition & 1 deletion assets/js/dist/pageviews.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 3493bc2

Please sign in to comment.