October 11, 2015 10:27 am

Creating a HTML5 app that shows gags in real-time Part 1

In developing the app, we aim to teach you two new features of HTML5 – the Notifications API which allows websites to show desktop notifications to their visitors and HTML5’s Web Workers which allow us to run JavaScript in the background without affecting the UI (user interface). The Notifications API would show an arbitrary message to the user no matter if his browser is currently in focus. For this to happen, a tab from your website must exist and the user must allow your website to push desktop notifications to him.

Creating a HTML5 app that shows gags in real-time 1

The app will use a web worker to retrieve the latest gags from the Infinigag API each minute and if a new gag comes – it will add it to the webpage and push a desktop notification. Users would be able to select the category of gags they are interested in – those being hot, trending and fresh (new).

Our app’s dependencies would be jQuery and Twitter’s Bootstrap stylesheet.
The final app would have the following functionality and looks:

Creating a HTML5 app that shows gags in real-time

HTML

We load our dependencies in our head element along with the page’s own JavaScript code:

Our one and only page does not contain much markup. In it, we add a first-level heading which will declare what the app is about and create a form which will be handled by JavaScript (it will not trigger a page reload/submission) in which we add a select box with the different categories of gags we can show to the user as options. Finally, we define an empty div container where the gags will appear.

JavaScript

Afterwards, in our app.js file which handles the notifications and the interaction with the Web Worker we create a new Worker when the page has loaded:

Now, when the user chooses a category (clicks on the Start Viewing button)  we send a message to the worker with the category that the user specified and clear all previous gags.

Then, when the worker sends us a message in return we check if the message is showing how many new gags are there. If it is showing us the number of new gags, we call a function which will show a desktop notification to the user using the Notifications API. If it is not about the number of new gags, we just add the message as markup to the div with an id of output (the messages given by the worker would contain valid markup composed of the new gags which can be directly added to the page).

Author Ivan Dimov

Ivan is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling. You can find more about him at: http://www.dimoff.biz. facebook, twitter


Tutorial Categories: