Skip to content

Instantly share code, notes, and snippets.

@bvaughn
Created August 27, 2021 22:53
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 bvaughn/6bded1e53cefda052ffafcec83ae46d6 to your computer and use it in GitHub Desktop.
Save bvaughn/6bded1e53cefda052ffafcec83ae46d6 to your computer and use it in GitHub Desktop.
Network caching test harness
<!DOCTYPE html>
<html>
<head></head>
<body>
<select id="cacheModeSelect">
<option>default</option>
<option>force-cache</option>
</select>
<script type="text/javascript">
URL = 'https://unpkg.com/jquery@3.6.0/dist/jquery.js';
const script = document.createElement('script');
script.src = URL;
document.body.appendChild(script);
</script>
<button id="loadFileButton">Load file</button>
<button id="loadFileWorkerButton">Load file from worker</button>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
const worker = new Worker('worker.js');
const fetchOptions = {
cache: 'default',
};
const cacheModeSelect = document.getElementById('cacheModeSelect');
cacheModeSelect.addEventListener('change', () => {
fetchOptions.cache = cacheModeSelect.value;
worker.postMessage({ type: 'set-cache-mode', value: cacheModeSelect.value });
});
const loadFileButton = document.getElementById('loadFileButton');
loadFileButton.addEventListener('click', () => {
fetchFile(URL);
});
const loadFileWorkerButton = document.getElementById('loadFileWorkerButton');
loadFileWorkerButton.addEventListener('click', () => {
worker.postMessage({ type: 'fetch-file', value: URL });
});
function fetchFile(url) {
performance.mark('loadFile-start');
fetch(url, fetchOptions).then(() => {
performance.mark('loadFile-end');
performance.measure('loadFile', 'loadFile-start', 'loadFile-end');
});
}
const fetchOptions = {
cache: 'default',
};
self.addEventListener('message', ({data}) => {
switch (data.type) {
case 'fetch-file':
fetchFile(data.value);
break;
case 'set-cache-mode':
fetchOptions.cache = data.value;
break;
}
});
function fetchFile(url) {
performance.mark('loadFile-start');
fetch(url, fetchOptions).then(() => {
performance.mark('loadFile-end');
performance.measure('loadFile', 'loadFile-start', 'loadFile-end');
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment