Programming for the Web - Getting Started with Coding - Coding For Dummies (2015)

Coding For Dummies (2015)

Part I. Getting Started with Coding

Chapter 2. Programming for the Web

In This Chapter

arrow Seeing the code powering websites you use every day

arrow Understanding the languages used to make websites

arrow Learning how applications are created for mobile devices

To think you can start something in your college dorm room … and build something a billion people use is crazy to think about. It’s amazing.

—Mark Zuckerberg

Programming for the web allows you to reach massive audiences around the world faster than ever before. Four years after its 2004 launch, Facebook had 100 million users, and by 2012 it had over a billion. By contrast, it took desktop software years to reach even 1 million people. These days, mobile phones are increasing the reach of web applications. Although roughly 300 million desktop computers are sold every year, almost 2 billion mobile phones are sold in that time — and the number is steadily increasing.

In this chapter you learn how websites are displayed on your computer or mobile device. I introduce the languages used to program websites, and show you how mobile-device applications are made.

Displaying Web Pages on Your Desktop and Mobile Device

On desktop computers and mobile devices, web pages are displayed by applications called browsers. The most popular web browsers include Google Chrome, Mozilla Firefox (formerly Netscape Navigator), Microsoft Internet Explorer, and Apple Safari. Until now, you have likely interacted with websites you visit as an obedient user, and followed the rules the website has created by pointing and clicking when allowed. The first step to becoming a producer and programmer of websites is to peel back the web page, and see and play with the code underneath it all.

Hacking your favorite news website

What’s your favorite news website? By following a few steps, you can see and even modify the code used to create that website. (No need to worry, you won’t be breaking any rules by following these instructions.)

tip.eps Although you can use almost any modern browser to inspect a website’s code, these instructions assume you’re using the Google Chrome browser. Install the latest version by going to www.google.com/chrome/browser.

To “hack” your favorite news website, follow these steps:

1. Open your favorite news website using the Chrome browser. (In this example, I use www.huffingtonpost.com.)

2. Place your mouse cursor over any static fixed headline and right-click once, which opens a contextual menu. Then, left-click once on the Inspect Element menu choice. (See Figure 2-1.)

9781118951309-fg0201.tif

Figure 2-1: Right-click on a headline and select Inspect Element from the menu.

tip.eps If using a Macintosh computer, you can right-click by holding down the Control key and clicking once.

The Developer Tools panel opens at the bottom of your browser. This panel shows you the code used to create this web page! Highlighted in blue is the specific code used to create the headline where you originally put your mouse cursor. (See Figure 2-2.)

9781118951309-fg0202.tif

Figure 2-2: The blue highlighted code is used to create the web page headline.

tip.eps Look at the left edge of the highlighted code. If you see a right arrow, left-click once on the arrow to expand the code.

3. Scan the highlighted code carefully for the text of your headline. When you find it, double-click on the headline text. This allows you to edit the headline. (See Figure 2-3.)

Be careful not to click on anything that begins with http, which is the headline link. Clicking on a headline link will open a new window or tab and load the link.

9781118951309-fg0203.tif

Figure 2-3: Double-click the headline text to edit it with your own headline.

4. Insert your name in the headline and press Enter.

Your name now appears on the actual web page. (See Figure 2-4.) Enjoy your newfound fame!

9781118951309-fg0204.tif

Figure 2-4: You successfully changed the headline of a major news website.

tip.eps If you were unable to edit the headline after following these steps, visit http://goggles.webmaker.org for an easier, more guided tutorial. It’s a foolproof guided version to edit code on a page. It’s a teaching aid that shows that any code on the Internet can be modified. On that page, click the yellow Activate X-Ray Goggles to see and edit the code on the webmaker.org web page. Try again to hack your favorite news website by following the “Remix Any Webpage” instructions.

If you successfully completed the steps above and changed the original headline, it’s time for your 15 minutes of fame to come to an end. Reload the web page and the original headline reappears. What just happened? Did your changes appear to everyone visiting the web page? And why did your edited headline disappear?

To answer these questions, you first need to understand how the Internet delivers web pages to your computer.

Understanding how the World Wide Web works

After you type a URL, such as huffingtonpost.com, into your browser, the following steps happen behind the scenes in the seconds before your page loads (see Figure 2-5):

1. Your computer sends your request for the web page to a router. The router distributes Internet access throughout your home or workplace.

2. The router passes your request onto your Internet service provider (ISP). In the United States, your ISP is a company like Comcast, Time Warner, AT&T, or Verizon.

3. Your ISP then converts the words and characters in your URL — “huffingtonpost.com,” in my example — into a numerical address called the Internet protocol address (or, more commonly, IP address). An IP address is a set of four numbers separated by periods (such as, for example, 192.168.1.1). Just like your physical address, this number is unique, and every computer has one. Your ISP has a digital phone book, similar to a physical phonebook, called a domain name server that’s used to convert text URLs into IP addresses.

4. With the IP address located, your ISP knows which server on the Internet to forward your request to, and your personal IP address is included in this request.

5. The website server receives your request, and sends a copy of the web page code to your computer for your browser to display.

6. Your web browser renders the code onto the screen.

9781118951309-fg0205.tif

Figure 2-5: Steps followed to deliver a website to your browser.

When you edited the website code using the Developer Tools, you modified only the copy of the website code that exists on your computer, so only you could see the change. When you reloaded the page, you started steps 1 through 6 again, and retrieved a fresh copy of the code from the server, overwriting any changes you made on your computer.

tip.eps You may have heard of a software tool called an ad blocker. Ad blockers work by editing the local copy of website code, just as you did above, to remove website advertisements. Ad blockers are controversial because websites use advertising revenue to pay for operating costs. If ad blockers continue rising in popularity, ad revenue could dry up, and websites would have to demand that readers pay to see their content.

Watching out for your front end and back end

Now that you know how your browser accesses websites, let us dive deeper into the way the actual website is constructed. As shown in Figure 2-6, the code for websites, and for programs in general, can be divided into four categories, according to the code’s function:

· Appearance: Appearance is the visible part of the website, including content layout and any applied styling, such font size, font typeface, and image size. This category is called the front end and is created using languages like HTML, CSS, and JavaScript.

· Logic: Logic determines what content to show and when. For example, a New Yorker accessing a news website should see New York weather, whereas Chicagoans accessing the same site should see Chicago weather. This category is part of the group called the back end and is created using languages like Ruby, Python, and PHP. These back end languages can modify the HTML, CSS, and JavaScript that is displayed to the user.

· Storage: Storage saves any data generated by the site and its users. User-generated content, preferences, and profile data must be stored for retrieval later. This category is part of the back end and is stored in databases like MongoDB and MySQL.

· Infrastructure: Infrastructure delivers the website from the server to you, the client machine. When the infrastructure is properly configured, no one notices it, but it can become noticeable when a website becomes unavailable due to high traffic from events like presidential elections, the Super Bowl, and natural disasters.

Usually, website developers specialize in one or at most two of these categories. For example, an engineer might really understand the front end and logic languages, or specialize in only databases. Website developers have strengths and specializations, and outside of these areas their expertise is limited, much in the same way that Jerry Seinfeld, a terrific comedy writer, would likely make a terrible romance novelist.

technicalstuff.eps The rare website developer proficient in all four of these categories is referred to as a full stack developer. Usually, smaller companies hire full stack developers, whereas larger companies require the expertise that comes with specialization.

9781118951309-fg0206.tif

Figure 2-6: Every website is made up of four different parts.

Defining web and mobile applications

Web applications are websites you visit using a web browser on any device. Websites optimized for use on a mobile device, like a phone or tablet, are called mobile web applications. By contrast, native mobile applications cannot be viewed using a web browser. Instead, native mobile applications are downloaded from an app store like the Apple App Store or Google Play, and designed to run on a specific device such as an iPhone or an Android tablet. Historically, desktop computers outnumbered and outsold mobile devices, but recently two major trends in mobile usage have occurred:

· In 2014, people with mobile devices outnumbered people with desktop computers. This gap is projected to continue increasing, as shown in Figure 2-7.

· Mobile-device users spend 80 percent of their time using native mobile applications, and 20 percent of their time browsing mobile websites.

9781118951309-fg0207.tif

Figure 2-7: Mobile devices have increased at a faster pace than desktops.

The increase in mobile devices has happened so quickly over the last 10 years that many companies are becoming “mobile first,” designing and developing the mobile version of their applications before the desktop version. WhatsApp and Instagram, two popular mobile applications, first built mobile applications, which continue to have more functionality then their regular websites.

Coding Web Applications

Web applications are easier to build than mobile applications, require little to no additional software to develop and test, and run on all devices, including desktop, laptops, and mobile. Although mobile applications can perform many common web-application tasks, such as email, some tasks are still easier to perform using web applications. For example, booking travel is easier using web applications, especially since the steps necessary — reviewing flights, hotels, and rental cars, and then purchasing all three — are best achieved with multiple windows, access to a calendar, and the entry of substantial personal and payment information.

The programming languages used to code basic web applications, further defined in the following sections, include HTML (Hypertext Markup Language), CSS (Cascading Style Sheets), and JavaScript. Additional features can be added to these websites using languages like Python, Ruby, or PHP.

Starting with HTML, CSS, and JavaScript

Simple websites, such as the one shown in Figure 2-8, are coded using HTML, CSS, and JavaScript. HTML is used to place text on the page, CSS is used to style that text, and JavaScript is used to add interactive effects like the Twitter or Facebook Share button that allows you to share content on social networks and updates the number of other people who have also shared the same content. Websites conveying mainly static, unchanging information are often coded only in these three languages. You will learn about each of these languages in later chapters.

Adding logic with Python, Ruby, or PHP

Websites with more advanced functionality, such as user accounts, file uploads, and e-commerce, typically require a programming language to implement these features. Although Python, Ruby, and PHP are not the only programming languages these sites can use, they are among the most popular. This popularity means there are large online communities of developers who program in these languages, freely post code that you can copy to build common features, and host public online discussions that you can read for solutions to common issues.

9781118951309-fg0208.tif

Figure 2-8: The lindaliukas.fi website, built using HTML, CSS, and JavaScript.

Each of these languages also has popular and well documented frameworks. A framework is a collection of generic components, such as user accounts and authentication schemes that are reused frequently, allowing developers to build, test, and launch websites more quickly. You can think of a framework as similar to the collection of templates that comes with a word processor. You can design your resume, greeting card, or calendar from scratch, but using the built-in template for each of these document types helps you create your document faster and with greater consistency. Popular frameworks for these languages include

· Django and Flask for Python

· Rails and Sinatra for Ruby

· Zend and Laravel for PHP

Coding Mobile Applications

Mobile applications are hot topics today, in part because mobile apps such as WhatsApp and Instagram were acquired for billions of dollars, and mobile app companies like Rovio, makers of Angry Birds, and King Digital, makers of Candy Crush, generate annual revenues of hundreds of millions to billions of dollars.

When coding mobile applications, developers can either build

· Mobile web applications, using HTML, CSS, and JavaScript.

· Native mobile applications using a specific language. For example, Apple devices are programmed using Objective-C or Swift, and Android devices are programmed using Java.

The choice between these two options may seem simple, but there are a few factors at play. Consider the following:

· Companies developing mobile web applications must make sure the mobile version works across different browsers, different screen sizes, and even different manufacturers, such as Apple, Samsung, RIM, and Microsoft. This results in thousands of possible phone combinations, which can greatly increase the complexity of testing needed before launch. Native mobile apps run only on one phone platform, so there is less variation to account for.

· Despite running on only one platform, native mobile apps are more expensive and take longer to build than mobile web apps.

· Some developers have reported that mobile web applications have more performance issues and load more slowly than native mobile applications.

· As mentioned before, users are spending more time using native mobile applications and less time using browser-based mobile web apps.

· Native mobile apps are distributed through an app store, which may require approval from the app store owner, whereas mobile web apps are accessible from any web browser. For example, Apple has a strict approval policy and takes up to six days to approve an app for inclusion in the Apple App Store, while Google has a more relaxed approval policy and takes two hours to approve an app.

technicalstuff.eps In one famous example of an app rejected from an app store, Apple blocked Google from launching the Google Voice app in the Apple App Store because it overlapped with Apple’s own phone functionality. Google responded by creating a mobile web app accessible from any browser, and Apple could do nothing to block it.

If you’re making this choice, consider the complexity of your application. Simple applications, like schedules or menus, can likely be cheaply developed with a mobile web app, whereas more complex applications, like messaging and social networking, may benefit from having a native mobile app. Even well-established technology companies struggle with this choice. Initially, Facebook and LinkedIn created mobile web applications, but both have since shifted to primarily promoting and supporting native mobile apps. The companies cited better speed, memory management, and developer tools as some of the reasons for making the switch.

Building mobile web apps

Although any website can be viewed with a mobile browser, those websites not optimized for mobile devices look a little weird, as if the regular website font size and image dimensions were decreased to fit on a mobile screen. (See Figure 2-9.) By contrast, websites optimized for mobile devices have fonts that are readable, images that scale to the mobile device screen, and a vertical layout suitable for a mobile phone.

Building mobile web apps is done using HTML, CSS, and JavaScript. CSS controls the website appearance across devices based on the screen width. Screens with a small width, such as those on phones, are assigned one vertically-based layout, whereas screens with a larger width, like those on tablets, are assigned another, horizontally-based layout. Because mobile web apps are accessed from the browser, and are not installed on the user’s device, these web apps can’t send push notifications (alerts) to your phone, run in the background while the browser is minimized, or communicate with other apps.

Although you can write the HTML, CSS, and JavaScript for your mobile web app from scratch, mobile web frameworks allow you to develop from a base of pre-written code, much like the frameworks for programming languages I mentioned earlier. These mobile web frameworks include a collection of generic components that are reused frequently, and allow developers to build, test, and launch websites more quickly. Twitter Bootstrap is one such mobile web framework, which I introduce in Chapter 8.

9781118951309-fg0209.tif

Figure 2-9: Left: starbucks.com not optimized for mobile. Right: starbucks.com optimized for mobile.

Building native mobile apps

Native mobile apps can be faster, more reliable, and look more polished than mobile web apps, as shown in Figure 2-10. Built using Java for use on Android devices, and Objective-C or Swift for use on Apple devices (iOS), native mobile apps must be uploaded to an app store, which may require approvals. The main benefit of an app store is its centralized distribution, and the app may be featured in parts of the app store that can drive downloads. Also, since native mobile applications are programs that are installed on the mobile device, they can be used in more situations without an Internet connection. Finally, and most importantly, users appear to prefer native mobile apps to mobile web apps by a wide margin, one that continues to increase.

Native mobile apps can take advantage of features that run in the background while the app is minimized, such as push notifications, and communicate with other apps, and these features are not available when creating a mobile web app. Additionally, native mobile apps perform better when handling graphics-intensive applications, such as games. To be clear, native mobile apps offer better performance and a greater number of features, but they require longer development times and are more expensive to build than mobile web apps.

9781118951309-fg0210.tif

Figure 2-10: Left: facebook.com native mobile app. Right: facebook.com mobile web app.

There is an alternative way to build a native mobile app — a hybrid approach that involves building an app using HTML, CSS, and JavaScript, packaging that code using a “wrapper,” and then running the code inside a native mobile app container. The most popular “wrapper” is a product called PhoneGap, and it recognizes specific JavaScript commands that allow access to device-level functionality that’s normally inaccessible to mobile web applications. After one version of the app is built, native mobile app containers can be launched for up to nine platforms including Apple, Android, Blackberry, and Windows Phone. The major advantage to using this hybrid approach is building your app once, and then releasing it to so many platforms simultaneously.

tip.eps Imagine you knew how to play the piano, but you wanted to also learn how to play the violin. One way you could do this is to buy a violin and start learning how to play. Another option is to buy a synthesizer keyboard, set the tone to violin, and play the keyboard to sound like a violin. This is similar to the hybrid approach, except, in this example, the piano is HTML, CSS, and JavaScript, the violin is a native iOS app, and the synthesizer keyboard is a wrapper like PhoneGap. Just like the synthesizer keyboard can be set to violin, cello, or guitar, so too can PhoneGap create native apps for Apple, Android, and other platforms.


What about all those other programming languages? (C, Java, and so on)

You may wonder why so many languages exist, and what they all do. Programming languages are created when a developer sees a need not addressed by the current languages. For example, Apple recently created the Swift programming language to make developing iPhone and iPad apps easier than Objective-C, the current programming language used. After they’re created, programming languages are very similar to spoken languages, like English or Latin. If developers code using the new language, then it thrives and grows in popularity, like English has over the last six centuries; otherwise, the programming language suffers the same fate as Latin, and becomes a dead language.

You may remember languages like C++, Java, and FORTRAN. These languages still exist today, and they’re used in more places than you might think. C++ is preferred when speed and performance is extremely important, and is used to program web browsers, such as Chrome, Firefox, and Safari, along with games like Call of Duty, and Counter Strike. Java is preferred by many large-scale business, and is also the language used to program apps for the Android phone. Finally, FORTRAN is not as widespread or popular as it once was, but it is popular within the scientific community, and it powers some functionality in the financial sector, especially at some of the largest banks in the world, many of which continue to have old code.

As long as programmers think of faster and better ways to program, new programming languages will continue to be created, while older languages fall out of favor.