javascript加载缓慢,代码似乎很大?

时间:2018-05-12 20:51:01

标签: javascript performance

所以这是我的代码

function listview() {

   //li list//
   var li = document.getElementById("sortcontainer").
getElementsByClassName("game");


for(var i = 0; i < li.length; i) {
   li[i].className = "lilistview";
   }

   //li image list//
   var img = document.getElementById("sortcontainer").
   getElementsByClassName("image");
for(var j = 0; j < img.length; j) {
   img[j].className = "imglistview";
   }   

     //header list//
   var header1 = document.getElementById("sortcontainer").
   getElementsByClassName("title");
   var header2 = document.getElementById("sortcontainer").
   getElementsByClassName("date");
   var header3 = document.getElementById("sortcontainer").
   getElementsByClassName("thumbrating");
for(var k = 0; k < header1.length; k) {
   header1[k].className = "listviewchildren";
   } 
for(var l = 0; l < header2.length; l) {
   header2[l].className = "listviewchildren";
   } 
for(var m = 0; m < header3.length; m) {
   header3[m].className = "listviewchildren";
   }

}  

它一遍又一遍地使用相同的代码将缩略图视图更改为列表视图,但代码看起来很长,而且从两者变化很慢。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

编辑:我在一夜之间思考之后重新整理了一切 1)这比我的利益更重要。
2)你正在改变ClassNames,对吗? 3)获取var sortcontainer = ..一次而不是5次 4)“for(var i = 0; i&lt; li.length; i){..”将循环,除非li.length为零。
5)一个例程将处理所有5组元素 6)必须加载页面。

window.onload = function() {
  var sortcontainer = document.getElementById("sortcontainer"); // used many times
  listview();
}
function listview() {
  changeClass("game", "lilistview");
  changeClass("image", "imglistview");
  changeClass("title", "listviewchildren");
  changeClass("date", "listviewchildren");
  changeClass("thumbrating", "listviewchildren");
}
function changeClass(oldClassName, newClassName) {
  var elementsByClass = sortcontainer.getElementsByClassName(oldClassName);
  console.log("-- " + oldClassName + " -- " + newClassName + " --");
  console.log("changing " + elementsByClass.length + " classnames");
  for (i=0; i<elementsByClass.length; i+=1) {
    elementsByClass[i].className = newClassName); }
}