Skip to content

Instantly share code, notes, and snippets.

@RiFi2k
Created March 20, 2019 02:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RiFi2k/4a266cc95842ae88e2c58c93d08df917 to your computer and use it in GitHub Desktop.
Save RiFi2k/4a266cc95842ae88e2c58c93d08df917 to your computer and use it in GitHub Desktop.
Web Worker Network Connection - https://github.com/collective/experimental.bwtools
(function(jQuery) {
jQuery(window).load(function() {
var cookie_name = '_bw';
function get_cookie() {
var keyValue = document.cookie.match('(^|;) ?' + cookie_name + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}
function set_cookie(value) {
var expires = new Date();
expires.setTime(expires.getTime() + (5 * 60 * 1000)); // 5min
document.cookie = cookie_name + '=' + value + ';path=/;expires=' + expires.toUTCString();
}
/**
* If we don't have the cookie call a worker to do some measurements
* and store the results in the cookie
*/
if (!get_cookie()) {
var base_url = PORTAL_URL + '/++plone++experimental.bwtools';
if (typeof(Worker) === 'undefined') {
return; // unsupported
}
w = new Worker(base_url + "/scripts/worker.js");
w.postMessage({
base_url: base_url
});
w.onmessage = function(event) {
if (event.data) {
set_cookie(event.data);
}
};
}
});
}(jQuery));
/**
* This function performs a synchronous request
* and returns an object contain informations about the download
* time and size
*/
function measure(filename) {
var xhr = new XMLHttpRequest();
var measure = {};
xhr.open("GET", filename + '?' + (new Date()).getTime(), false);
measure.start = (new Date()).getTime();
xhr.send(null);
measure.end = (new Date()).getTime();
measure.len = parseInt(xhr.getResponseHeader('Content-Length') || xhr.responseText.length || 0);
measure.delta = measure.end - measure.start;
return measure;
}
/**
* Requires that we pass a base url to the worker
* The worker will measure the download time needed to get
* a ~0KB and a 100KB.
* It will return a string that serializes this informations as
* pipe separated values
*/
onmessage = function(e) {
measure0 = measure(e.data.base_url + '/test/0.bz2');
measure100 = measure(e.data.base_url + '/test/100K.bz2');
postMessage(
measure0.delta + '|' +
measure0.len + '|' +
measure100.delta + '|' +
measure100.len
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment