Richard Hewett
Richard Hewett

Reputation: 45

Slow javascript loading, code seems very big?

So here is my code

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";
   }

}  

It bassically uses the same code over and over again to change a thumbnail view to a list view but the code seems so long, and is slow to change from the two.

Any suggestions?

Upvotes: 0

Views: 46

Answers (1)

dcromley
dcromley

Reputation: 1410

EDIT: I redid the whole thing after thinking about it overnight.
1) This is more for my benefit than yours.
2) You are changing ClassNames, right?
3) Get var sortcontainer = .. once instead of 5 times.
4) The "for (var i=0; i<li.length; i) { .." will loop unless li.length is zero.
5) One routine will handle all 5 sets of elements.
6) The page has to be loaded.

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); }
}

Upvotes: 1

Related Questions