Skip to content

Instantly share code, notes, and snippets.

@sk8terboi87
Last active May 11, 2022 06:37
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sk8terboi87/32699d5a3a9bcbdd10d7b94316f54ccd to your computer and use it in GitHub Desktop.
Save sk8terboi87/32699d5a3a9bcbdd10d7b94316f54ccd to your computer and use it in GitHub Desktop.
JavaScript Web Worker Example: Fetching Random Content from Wikipedia using Web Workers. http://codelikeapoem.com/2017/03/web-workers-beginners-guide.html
<!DOCTYPE html>
<html>
<head>
<title>Polling Example</title>
<style type="text/css">
.title, .result {
display: inline-block;
padding: 10px;
background-color: #fffeee;
}
.content {
padding: 10px;
background-color: #fffdd8;
}
</style>
</head>
<body>
<p>Simple polling example to detect changes in content</p>
<div class="result">
<span class="title">Loading...</span>
<div class="content">Loading...</div>
</div>
<script type="text/javascript">
//--- Creating a Web Worker Named 'pollingWorker.js' ---//
var pollingWorker = new Worker('pollingWorker.js');
//--- We are Listening to the Worker ---//
pollingWorker.addEventListener('message', function contentReceiverFunc(e) {
document.querySelector('.result .title').innerText = e.data.title;
document.querySelector('.result .content').innerHTML = e.data.content;
});
</script>
</body>
</html>
function fetchRandomContent() {
//-- We are using FETCH API to get the contents --//
fetch('https://en.wikipedia.org/w/api.php?format=json&origin=*&action=query&generator=random&rvprop=content&prop=revisions', {
method: 'GET',
mode: 'cors',
headers: {
'Content-Type': 'application/json'
},
credentials: "same-origin"
}).then(function(promise) {
promise.json().then(function(response) {
//--- Parsing Wikipedia data ---//
var data = {},
keys = Object.keys(response.query.pages),
key = keys[0];
data.title = response.query.pages[key].title
data.content = response.query.pages[key].revisions[0]["*"]
//--- Parsing Wikipedia data ---//
//--- Sending message to our application ---//
self.postMessage(data);
});
}, function(error) {
console.log('shit!', error);
});
}
setInterval(function() {
fetchRandomContent();
}, 5000);
@leoplaw
Copy link

leoplaw commented Jul 31, 2021

Thanks for this! It was very helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment