Set up the files and namespaces

Một phần của tài liệu single page web applications (Trang 88 - 93)

We’ll set up our files and namespaces according to the code standards found in appendix A. In particular, we’ll have one JavaScript file per JavaScript namespace, and use self-executing anonymous functions to prevent pollution of the global namespace.

We’ll also set up CSS files in a parallel structure. This convention speeds development, improves quality, and eases maintenance. Its value increases as we add more modules and developers to the project.

3.2.1 Create the file structure

We’ve selected spa for the root namespace of our application. We synchronize the JavaScript and CSS file names, the JavaScript namespace, and the CSS selector names.

This makes it much easier to track which JavaScript goes with which CSS.

PLAN THE DIRECTORIES AND FILES

Web developers often place their HTML file in a directory and then place their CSS and JavaScript in subdirectories. We see no reason to break convention. Let’s create the directories and files as shown in listing 3.1:

spa +-- css

| +-- spa.css

| `-- spa.shell.css +-- js

| +-- jq

| +-- spa.js

| `-- spa.shell.js +-- layout.html

`-- spa.html

Listing 3.1 Files and directories, first pass

spa is our root directory and our root namespace.

This is the directory that contains all of our stylesheet files.

This is the directory that contains all our JavaScript files.

This is the directory that contains jQuery JavaScript files, including plugins.

spa.js provides our root JavaScript namespace, spa. This has a corresponding stylesheet at css/

spa.css.

spa.shell.js provides the Shell namespace, spa.shell. This has a corresponding stylesheet at css/

spa.shell.css. This is the file read

by the browser to run our SPA.

Now that we have the basics in place, let’s get jQuery installed.

INSTALL JQUERY AND A PLUGIN

jQuery and its plugins are often offered as either minified or regular files. We almost always install the regular files because this helps in debugging, and we minimize as part of our build system anyway. Don’t worry about what they do yet—we’ll get to that later in the chapter.

The jQuery library provides useful cross-platform DOM manipulation and other utilities. We’re using version 1.9.1, which is available from http://docs.jquery.com/

Downloading_jQuery. Let’s place it in our jQuery directory:

...

+-- js

| +-- jq

| | +-- jquery-1.9.1.js ...

The jQuery uriAnchor plugin provides utilities to manage the anchor component of the URI. It’s available from github at https://github.com/mmikowski/urianchor.

Let’s place it in the same jQuery directory:

...

+-- js

| +-- jq

| | +-- jquery.uriAnchor-1.1.3.js ...

Our files and directories should now look like listing 3.2:

spa +-- css

| +-- spa.css

| `-- spa.shell.css +-- js

| +-- jq

| | +-- jquery-1.9.1.js

| | `-- jquery.uriAnchor-1.1.3.js

| +-- spa.js

| `-- spa.shell.js +-- layout.html

`-- spa.html

Now that we have all of our files in place, it’s time to start writing some HTML, CSS, and JavaScript.

3.2.2 Write the application HTML

When we open our browser document (spa/spa.html) we can bask in all the SPA goodness we’ve wrought so far. Of course, because this is an empty file, the goodness provided is limited to a bug-free, highly secure blank page that does absolutely noth- ing. Let’s change the “blank page” part.

Listing 3.2 Files and directories after adding jQuery and plugin

65 Set up the files and namespaces

The browser document (spa/spa.html) will always remain small. Its only role is to load libraries and stylesheets, and then start our application. Let’s fire up our favorite text edi- tor and add all the code we’ll need to get through this chapter, as shown in listing 3.3:

<!doctype html>

<html>

<head>

<title>SPA Starter</title>

<!-- stylesheets -->

<link rel="stylesheet" href="css/spa.css" type="text/css"/>

<link rel="stylesheet" href="css/spa.shell.css" type="text/css"/>

<!-- third-party javascript -->

<script src="js/jq/jquery-1.9.1.js" ></script>

<script src="js/jq/jquery.uriAnchor-1.1.3.js"></script>

<!-- our javascript -->

<script src="js/spa.js" ></script>

<script src="js/spa.shell.js"></script>

<script>

$(function () { spa.initModule( $('#spa') ); });

</script>

</head>

<body>

<div id="spa"></div>

</body>

</html>

The performance conscious developers in the audience might ask “Why don’t we put scripts at the end of the body container like traditional web pages?” That is a fair ques- tion, because this usually allows the page to render faster, as static HTML and CSS can be displayed before the JavaScript finishes loading. SPAs don’t work like that, though.

They generate the HTML with JavaScript, and therefore placing the scripts outside the header doesn’t result in faster rendering. Instead, we keep all of the external scripts in the head section to improve organization and legibility.

3.2.3 Create the root CSS namespace

Our root namespace is spa, and per our convention from appendix A our root stylesheet should be called spa/css/spa.css. We previously created this file, but now it’s time to populate it. Because this is our root stylesheet, it’ll have a few more sections than our other CSS files. Let’s again use our favorite text editor to add the rules we need, as shown in listing 3.4:

/*

* spa.css

* Root namespace styles

Listing 3.3 Application HTML—spa/spa.html

Listing 3.4 The root CSS namespace—spa/css/spa.css

Load stylesheets first. This optimizes performance. If we add third-party stylesheets, we should load them first.

Load third-party JavaScript next. At present, the only third-party scripts we’re loading are jQuery and the plugin for anchor manipulation.

Load our JavaScript libraries next. They should be ordered by depth of namespace.

This is important because our namespace object, spa, must be declared before we can declare its children, for example, spa.shell.

Initialize the application once the DOM is ready.

Those familiar with jQuery will notice our code uses shorthand, as $(function (...

could’ve been written as

$(document).ready(function (...

*/

/** Begin reset */

* {

margin : 0;

padding : 0;

-webkit-box-sizing : border-box;

-moz-box-sizing : border-box;

box-sizing : border-box;

}

h1,h2,h3,h4,h5,h6,p { margin-bottom : 10px; } ol,ul,dl { list-style-position : inside;}

/** End reset */

/** Begin standard selectors */

body {

font : 13px 'Trebuchet MS', Verdana, Helvetica, Arial, sans-serif;

color : #444;

background-color : #888;

}

a { text-decoration : none; }

a:link, a:visited { color : inherit; } a:hover { text-decoration: underline; } strong {

font-weight : 800;

color : #000;

}

/** End standard selectors */

/** Begin spa namespace selectors */

#spa {

position : absolute;

top : 8px;

left : 8px;

bottom : 8px;

right : 8px;

min-height : 500px;

min-width : 500px;

overflow : hidden;

background-color : #fff;

border-radius : 0 8px 0 8px;

}

/** End spa namespace selectors */

/** Begin utility selectors */

.spa-x-select {}

.spa-x-clearfloat {

height : 0 !important;

float : none !important;

visibility : hidden !important;

clear : both !important;

}

/** End utility selectors */

Reset most selectors. We don’t trust browser defaults. CSS authors will recognize this as a common practice, though not without controversy.

Adjust standard selectors. We again don’t trust browser defaults, and we also want to ensure a common look across the application for certain types of elements.

These can—and will—be adjusted by more specific selectors in other files.

Define namespace selectors.

Generally, this is the selector for an element using the root name, for example, #spa.

Provide utility selectors for use across all other modules. These are prefixed with spa-x-.

67 Set up the files and namespaces

Per our code standards, all CSS IDs and class names in this file are preceded by the spa- prefix. Now that we’ve created the root application CSS, we’ll create the corre- sponding JavaScript namespace.

3.2.4 Create the root JavaScript namespace

Our root namespace is spa, and per our convention from appendix A, our root JavaScript should be called spa/js/spa.js. The minimal JavaScript required is varspa= {};. But, we want to add a method to initialize the application, and we want to ensure that the code will pass JSLint. We can use the template from appendix A and pare it down because we don’t need all the sections. Let’s open the file with our second-most- favorite text editor and populate it as shown in listing 3.5:

/*

* spa.js

* Root namespace module

*/

/*jslint browser : true, continue : true, devel : true, indent : 2, maxerr : 50, newcap : true, nomen : true, plusplus : true, regexp : true, sloppy : true, vars : false, white : true

*/

/*global $, spa */

var spa = (function () {

var initModule = function ( $container ) {

$container.html(

'<h1 style="display:inline-block; margin:25px;">' + 'hello world!'

+ '</h1>' );

};

return { initModule: initModule };

}());

We want to ensure our code doesn’t have any common errors or bad practices. Appen- dix A shows how to install and run the valuable JSLint utility, which does just that. It describes what all the /*jslint ... */ switches at the top of our files mean. Besides the appendix, we also discuss JSLint further in chapter 5.

Let’s check our code by typing jslint spa/js/spa.js at the command line—we shouldn’t see any warnings or errors. We can now open our browser document (spa/

spa.html) and see the contract-mandated “hello world” demonstration as shown in fig- ure 3.2.

Now that we’ve greeted the world and are emboldened by the savory flavor of suc- cess, let’s embark on a more ambitious quest. In the next section, we start building our first “real-world” SPA.

Listing 3.5 The root JavaScript namespace—spa/js/spa.js

Set JSLint switches per the module template in appendix A.

Tell JSLint to expect the spa and $ global variables. If we find ourselves adding our own variables to this list after spa, we’re probably doing something wrong.

Use the module pattern from chapter 2 to create our “spa” namespace.

This module exports one method, initModule, which, as the name suggests, is a function that initializes the application.

Một phần của tài liệu single page web applications (Trang 88 - 93)

Tải bản đầy đủ (PDF)

(433 trang)