JavaScript_DOM programming art Chapter05 best practices, Chapter06 picture library improved version -- 20210427

Chapter05

link

Pseudo protocol

Pseudo protocol that can be used to link JavaScript functions: javascript:

<a href="javascript:function_name(parameter)">Example</a>

<a href="javascript:pop('http://www.baidu.com/')">Example</a>

This is a very bad practice. It can only be used in browsers that support pseudo protocol and JavaScript.

Stationary degradation

Failure examples of stationary degradation:

<!--If user disabled JavaScript,Then the link still fails-->
<a href="#" onclick="popUp(this.href);return false;">Example</a>

Successful examples of smooth degradation:

<!--If user disabled JavaScript,Then this link is still valid-->
<a href="http://www.example.com/" onclick="popUp(this.href);return false;">Example</a>

Progressive enhancement

CSS

Detach JavaScript

Package the JavaScript code in the prepareLinks function and add this function to the onload event of the window object.
#JavaScript file

window.onload = prepareLinks;
function prepareLinks(){
 var links = document.getElementsByTagName("a");
 for (var i=0; i<links.length;i++){
 	if (links[i].getAttribute("class") == "popup"){
 		links[i].onclick = function(){
 			popUp(this.getAttribute("href"));
 			return false;
 		}
 	}
 }
}

function popUp(winURL){
	window.open(winURL,"popup","width=320,height=480");
}

Backward compatibility

Web design should take into account the parsing ability of the old browser.

Object detection

Backward compatibility is the simplest solution.

if (method) {
    //statements
}


window.onload = function(){
	if (!document.getElementsByTagName) return false;
	 var links = document.getElementsByTagName("a");
 	for (var i=0; i<links.length;i++){
 		if (links[i].getAttribute("class") == "popup"){
 		links[i].onclick = function(){
 			popUp(this.getAttribute("href"));
 			return false;
 			}
 		}
 	}
}

However, the disadvantage of this scheme is that if there are multiple methods or attributes to detect, there will be a lot of nested or detection statements, which makes the code look bloated and difficult to read.

Browser sniffing Technology

In addition to detecting the existence of objects, you can also use browser sniffing. Improve the backward compatibility of JS by retrieving the brand and version of the browser. But there are risks, because sometimes the information of the browser is not standard, and the iterative update of the browser version makes this implementation more difficult.

Performance considerations

For the sake of web fluency, some issues should be considered.

Reduce DOM access and Tags

Minimize access to DOM and tags. When multiple functions will obtain a group of similar elements, you can consider reconstructing the code, saving the search results in a global variable, or passing a group of elements directly to the function in the form of parameters.

Merge and place scripts

Merging scripts can reduce the number of HTTP requests.
It is recommended to put all < script > tags at the end of the document. Before the tags, the page can be loaded faster.
The script located in the block will make the browser unable to load other files (such as pictures or other scripts) in parallel. Generally speaking, according to the HTTP specification, the browser can only download two files from the same domain name at most at the same time. During the script download, the browser will not download any other files, even files from different domain names, All other resources cannot be downloaded until the script is loaded. So it's recommended that all

Compression script

Compression script refers to deleting all unnecessary bytes (spaces, comments, etc.) in the script file. Although the compressed code has poor readability, it can greatly reduce the file size. In most cases, there should be two versions. One is the working copy, which can modify the code and add comments; The other is a compressed copy, which is used to put on the server. Usually, in order to distinguish the uncompressed version, it is best to add the word min to the file name of the compressed copy.
Recommended compression tools include Douglas Crockford's JSMin and Google's Closure Compiler.

Chapter06

Soul 5 questions:

Does it support smooth degradation?

"What happens if JavaScript is disabled?" = = > solve

<a href="images/fireworks.jpg" title="A fireworks display" onclick="showPic(this);return false;">Fireworks</a>

Is its JavaScript separated from HTML tags?

  • Add hook
    #gallery.html
        <ul id="imagegallery">
            <li>
                <a href="images/fireworks.jpg" title="A fireworks display" onclick="showPic(this);return false;">Fireworks</a>
            </li>
            <li>
                <a href="images/coffee.jpg" title="A cup of black coffee" onclick="showPic(this);return false;">Coffee</a>
            </li>
            <li>
                <a href="images/rose.jpg" title="A red,red rose" onclick="showPic(this);return false;">Rose</a>
            </li>
            <li>
                <a href="images/bigben.jpg" title="The famous clock" onclick="showPic(this);return false;">Big Ben</a>
            </li>
        </ul>
  • Add event handler
    #showPic.js
function prepareGallery(){
    if (!document.getElementsByTagName) return false;
    if (!document.getElementById) return false;
    if (!document.getElementById("imagegallery")) return false;
    var gallery = document.getElementById("imagegallery");
    var links = document.getElementsByTagName("a");
    for (var i=0; i<links.length; i++){
        links[i].onclick = function(){
            showPic(this);
            return false;
        }
    }
}
  • Shared onload event
    #showPic.js
# Method 1: establish anonymous function
window.onload = function(){
	firstFunction();
	secondFunction();
}

# Method 2: establish addLoadEvent function
function addLoadEvent(func){
	var oldonload = window.onload
	if (typeof window.onload != 'function'){
		window.onload = func;
	}
	else{
		window.onload = function(){
			oldonload();
			func();
		}
	}
}

addLoadEvent(firstFunction);
addLoadEvent(secondFunction);

Don't make too many assumptions

You need to check the elements in showPic() and modify prepareGallery() when the picture is normal but the text is abnormal.
#showPic.js

function showPic(whichpic){
    if (!document.getElementById("placeholder")) return false;
    var source = whichpic.getAttribute("href");
    var placeholder = document.getElementById("placeholder");
    placeholder.setAttribute("src",source);
    if (document.getElementById("description")){
    var text = whichpic.getAttribute("title");
    var descrition = document.getElementById("description");
    descrition.firstChild.nodeValue = text;
    }
}

function prepareGallery(){
    if (!document.getElementsByTagName) return false;
    if (!document.getElementById) return false;
    if (!document.getElementById("imagegallery")) return false;
    var gallery = document.getElementById("imagegallery");
    var links = document.getElementsByTagName("a");
    for (var i=0; i<links.length; i++){
        links[i].onclick = function(){
            return !showPic(this);
        }
    }
}

optimization

Add a ternary operator to check the title attribute (this is a brain racking method)
#showPic.js

    var text = whichpic.getAttribute("title")? whichpic.getAttribute("title"):"";

Keyboard access

It is better not to use the onkeypress event handler, which will be triggered every time the user presses a key. It is recommended to use the onclick event handler, which can also use the keyboard to Enter and click the link.

Combine JavaScript with CSS

Using hooks can be used in CSS style sheets.
#gallery.html

Insert code slice here

#layout.css

#imagegallery{
    list-style: none;
}
#imagegallery li{
    display: inline;
}

DOM Core and HTML-DOM

Following equivalence
document.getElementsByTagName("form");
document.forms;

placeholder.setAttribute("src",source);
placeholder.src = source;

Comprehensive code

#showPic.js

function showPic(whichpic){
    if (!document.getElementById("placeholder")) return false;
    var source = whichpic.getAttribute("href");
    var placeholder = document.getElementById("placeholder");
    placeholder.setAttribute("src",source);
    if (document.getElementById("description")){
    var text = whichpic.getAttribute("title")? whichpic.getAttribute("title"):"";
    var descrition = document.getElementById("description");
    descrition.firstChild.nodeValue = text;
    }
}

function prepareGallery(){
    if (!document.getElementsByTagName) return false;
    if (!document.getElementById) return false;
    if (!document.getElementById("imagegallery")) return false;
    var gallery = document.getElementById("imagegallery");
    var links = document.getElementsByTagName("a");
    for (var i=0; i<links.length; i++){
        links[i].onclick = function(){
            return !showPic(this);
        }
    }
}


function addLoadEvent(func){
	var oldonload = window.onload
	if (typeof window.onload != 'function'){
		window.onload = func;
	}
	else{
		window.onload = function(){
			oldonload();
			func();
		}
	}
}

#layout.css

body{
    font-family: "Helvetica","Arial",serif;
    color: #333;
    background-color: #ccc;
    margin: 1em 10%;
}
h1{
    color: #333;
    background-color: transparent;
}
a{
    color: #c60;
    background-color: transparent;
    font-weight: bold;
    text-decoration: none;
}
ul{
    padding: 0;
}
li{
    float:left;
    padding: 1em;
}
img{
    display: block;
    clear: both;
}
#imagegallery{
    list-style: none;
}
#imagegallery li{
    display: inline;
}

#gallery.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8"/>
        <title>
            Image Gallery
        </title>
        <link rel="stylesheet" href="styles/layout.css" type="text/css" media="screen">
    </head>
    <body>
        <h1>Snapshots</h1>
        <ul id="imagegallery">
            <li>
                <a href="images/fireworks.jpg" title="A fireworks display">Fireworks</a>
            </li>
            <li>
                <a href="images/coffee.jpg" title="A cup of black coffee">Coffee</a>
            </li>
            <li>
                <a href="images/rose.jpg" title="A red,red rose">Rose</a>
            </li>
            <li>
                <a href="images/bigben.jpg" title="The famous clock">Big Ben</a>
            </li>
        </ul>
        <img id="placeholder" src="images/placeholder.gif" alt="my image gallery">
        <p id="description">Choose an image.</p>
        <script src="scripts/showPic.js"></script>
    </body>
</html>

Keywords: Javascript Web Development html css

Added by tartou2 on Sat, 19 Feb 2022 01:59:27 +0200