Exercise Notes
GIFs
One nice thing to have on a webpage is GIFs. Let’s add some:
- Sign up for a Giphy Developer account and then click Create an App. Once you fill in some basic info you should be given an API key, which you can use to make requests to their API.
- Create some new files called
trending.html
,giphy.js
andrequests.js
. Add some HTML to yourtrending.html
file to get some basic content like a title and header. Now add styling in your CSS stylesheet and make sure to include a reference to both your stylesheet and yourgiphy.js
andrequests.js
scripts on your trending page. - Now let’s write some JavaScript in your
giphy.js
file that will populate the page with a list of the top 10 trending gifs. To get an idea of how to start, look at the GIPHY API Docs and Explorer, then check out this demo page that uses the Random endpoint to generate random gifs. Remember, make sure to use your own API key in your project! - The function calling the API should live in
requests.js
. For now, you can define it insiderequests.js
and call it insidegiphy.js
. As long as both scripts are added to the html, it will work. - The demo page uses the old XMLHttpRequest API to make requests to the Giphy site. Try changing this (or your own implementation) to the Fetch API.
- (As a stretch goal) Try combining this with async/await syntax.
Bundlers
We added gifs to our website. However, we had to add separate JavaScript scripts, to keep the code clean. This is not great for performance, as the browser has to make 2 separate calls for each JavaScript file. Let’s fix that:
- Initialise an npm project by using
npm init
command – for our little project, the default values should be enough - Install a bundler library – we recommend esbuild for this exercise:
npm install esbuild
- Create a new rule called
build
inside thescripts
section of thepackage.json
file:"build": "esbuild giphy.js --bundle --outfile=bundle.js"
- For the bundler to know where the request function is coming from, we need to:
- Run the rule you just created
npm run build
- Have a look into
bundle.js
to see what the bundler did - Back into your
trending.html
, remove the lines that includerequests.js
andgiphy.js
. Includebundle.js
instead. - Open your trending page and check if everything works as before!
Part 3 – Konami code
Try adding a Konami Code to your site.
Add a secret sequence of key presses to your page which triggers some behaviour – images raining from the sky and a sound effect, perhaps.
(Note: there are libraries which can do this for you, but you should be able to implement it yourself!)