Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment