Starting our web application

Now that we know how to compile a CoffeeScript file, let's use it in a web page! We'll create a simple web page that uses CoffeeScript to read a configuration object and insert text into the page. This page will be used by the owner of a small pet shop. We'll insert the owner's name dynamically, so it can be easily changed if needed. First let's create a simple index.html :

<!DOCTYPE html> <html> <head> <title>The Pet Shop</title> </head> <body> <h1>Welcome to <span id="owner_name"></span>'s Pet Shop</h1> <script src="setup.js"></script> </body> </html>

You'll notice that we have a script tag pointing to our JavaScript file, just like normal. The web application doesn't need to know anything about our CoffeeScript files. It will run the compiled JavaScript output, happily ignorant of the original source.

Note It is possible to make your browser aware of CoffeeScript, and make it run CoffeeScript code directly. However, this is an advanced technique and not really necessary to get you started, so throughout the book we will always compile to JavaScript and run that. If you'd like to learn more about this technique, see Chapter 10, Using CoffeeScript in more places.

Let's get rid of that annoying alert in setup.coffee , and update it with a configuration object and some code to insert the owner's name into the page heading. You probably know how you would write this in JavaScript. It's similar in CoffeeScript, so see if you can follow along:

shop = { owner: { name: "Ian" } } nameElement = document.getElementById("owner_name") nameElement.innerHTML = shop.owner.name

Now we'll run the compiler again so that it updates the JavaScript. This time, we'll pass it the whole directory as an argument instead of our single file. This will compile any CoffeeScript files it finds in the directory, which will come in handy later, when we have more than one CoffeeScript file.

coffee -c .

Our setup.js has been updated, so load index.html in a web page, and it should say Welcome to Ian's Pet Shop.