注意分离:
- 通过将CSS关闭来测试页面是否仍然可用,内容是否依然可读;
- 将JavaScript关闭来测试页面仍然可以执行正常功能;所有连接是否正常工作;所有的表单是否可以正常工作;
- 不使用内联处理器(onclick之类)和内联样式属性,因为这些不属于内容层;
- 使用语义上有意义的HTML元素;
DOM脚本:
- DOM访问: //DOM访问的代价是昂贵的 ;
- 避免在循环中使用DOM访问;
- 在可能的情况下使用selector API; /尽可能使用id,getElementById是最便捷的查找方法;
- 在HTML容器中重复使用时,缓存重复的次数;
- 将DOM引用分配给局部变量,并使用这些局部变量;
- 例子:
for (var i = 0; i < 100; i += 1) { document.getElementById('result').innerHTML += i + ' ,'; } //优化 var i, content = ' '; for(i = 0; i < 100; i +=1) { content += i + ' ,'; } document.getElementById('result1').innerHTML += content; -------------------------------- var padding = document.getElementById('result').style.padding, margin = document.getElementById('result').style.margin; //优化 var style = document.getElementById('result').style, padding = style.padding, margin = style.margin; ---------------------------- //更好的获取节点 ,IE8以上 document.querySelector(); document.querySelectorAll();
- 操纵DOM:更新DOM会导致浏览器重新绘制屏幕;所以尽量减少更新DOM;当需要创建相对比较大的子树时,采用文档碎片;
- 创建文档时例子:
//反模式,在创建时立即添加节点 var p,t; p = document.createElement('p'); t = document.createTextNode('first paragraph'); p.appendChild(t); document.body.appendChild(p); p = document.createElement('p'); t = document.createTextNode('second paragraph'); p.appendChild(t); document.body.appendChild(p); //优化, var p ,t , frag; frag = document.createDocumentFragment(); p = document.createElement('p'); t = document.createTextNode('first paragraph'); p.appendChild(t); frag.appendChild(p); p = document.createElement('p'); t = document.createTextNode('second paragraph'); p.appendChild(t); frag.appendChild(p); document.body.appendChild(frag);
- 更新文档时例子:
//cloneNode var oldnode = document.getElementById('result'); clone = oldnode.cloneNode(true); //处理克隆对象 var t = document.createTextNode('new text'); clone.appendChild(t); //replaceChild oldnode.parentNode.replaceChild(clone, oldnode);
- 创建文档时例子:
事件:
- 事件处理:
- 最简单地使用事件函数;//不要使用内联
- 最好使用监听器;
- 事件授权:利用事件冒泡,可以减少事件监听器的数量
<div id='click-wrap'> <button>Click me:0</button> <button>Click me too:0</button> <button>Click me three:0</button> </div> var target = document.getElementById('click-wrap'); target.addEventListener('click',function(e){ var src = e.target; if(src.nodeName.toLowerCase() !== 'button') return; alert(0); },false);
//注意以上实际情况中使用要考虑浏览器的兼容性;
长期运行脚本
//js没有线程,用其他方法模拟
- 使用setTimeout;
- 使用web workers (html5)
var ww = new Worker("test.js"); ww.onmessage = function(event) { document.body.innerHTML += "<p>message :" + event.data + "</p>"; } //test.js var end = 1e8, tmp = 1; postMessage("hello"); //Web Workers做了1e8次简单的计算 while(end) { end -= 1; tmp += end; if(end === 5e7) { postMessage('halfway there, `tmp` is now ' + tmp); } } postMessage("all done");