JavaScript Conventions
JavaScript Conventions
In JavaScript, there are several things that should be considered bad practice and avoided:
❑ Include All Script in External Documents - JavaScript code should only be included in external script files. Script should not be embedded in markup documents or be included inline, directly on markup elements.
❑ Write Clean, Consistent Code - JavaScript code should be neatly formatted and organized in a consistent, predicable way.
❑ Namespace JavaScript Code - JavaScript variables, functions, objects, and the like should be namespaced to minimize potential namespace conflicts and collisions with other JavaScript applications.
❑ Avoid Browser Detection - Browser detection should be avoided where possible. Instead, detect specific browser features.
Include All Script in External Documents
Part of making JavaScript non-obtrusive means making JavaScript complementary and supplemental, rather than required and mandatory. It should be noted why this is the best approach.
Consider the following code example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type"
content="application/xhtml+xml; charset=us-ascii" />
<title>Inline JavaScript</title>
<link rel='stylesheet' type='text/css' href='style.css' />
</head>
<body>
<img src='pumpkin.jpg' alt='Pumpkin' />
<a href='javascript:void(0);'
onclick='window.open(
"pumpkin.jpg",
"picture",
"scrollbars=no,width=300,height=280,resizable=yes"
);'>Open Picture</a>
</body>
</html>
Combine the preceding markup with the following style sheet:
img {
display: block;
margin: 10px auto;
width: 100px;
border: 1px solid rgb(128, 128, 128);
}
body {
font: 14px sans-serif;
}
p {
width: 150px;
text-align: center;
}
You would get something like...
Will upload it shortly.