3
\$\begingroup\$

Can you help me optimize the speed and security of my homepage?

(Link now dead - 2014/04/10 - http://www.pixel-klicker.de)

var aktiv=0;

var red ;

var enable = [];

var count = 1;

var number = 0;

var Jetzt = 0;
var Start = 0;  
var codes = [];

var xmlHttp;

function createXMLHttpRequestObject()
{

if(window.ActiveXObject){
    try{
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch(e){
        xmlHttp = false;
    }
}
else{
    try{
        xmlHttp = new XMLHttpRequest();
    }
    catch(e){
        xmlHttp = false;
    }
}
if(!xmlHttp)
    alert("Fehler beim erzeugen des XMLHttpRequest Objekts");
else
    return xmlHttp;
}

function process()
{
    if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){     
        xmlHttp.open("POST","ses.php",true);
        xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // WICHTIG FUER POST !!!
        xmlHttp.onreadystatechange = handleServerResponse;    
        xmlHttp.send(null);

    }
    else
        setTimeout("process()",1000);
}
function setStart()
{
        if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){       
                var value="zeit="+ Start; 
                xmlHttp.open("post","set.php",true);
                xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // WICHTIG FUER POST !!!                       
                xmlHttp.send(value);               

        }
        else
                setTimeout("setStart()",1000);
}

function getStart()
{
        if(xmlHttp.readyState == 4 || xmlHttp.readyState == 0){             
                xmlHttp.open("post","get.php",true);
                xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); // WICHTIG FUER POST !!!                       
                xmlHttp.onreadystatechange = handleServerResponse2;
                xmlHttp.send(null);

        }
        else{
                setTimeout("getStart()",1000);
        }

}

function handleServerResponse2(){
         if(xmlHttp.readyState == 4){

            if(xmlHttp.status == 200){
                    xmlResponse = xmlHttp.responseXML;
                    xmlDocumentElement = xmlResponse.documentElement;   
                    hrgData = xmlDocumentElement.firstChild.data;
                    var anzahl = document.getElementById("anzahl").value;
                    if(aktiv==0 && anzahl==0){

                        if(Start != hrgData){
                          alert("Du elendiger Betrüger! Fang von vorne an, aber dieses mal ohne zu bescheissen!");                           
                            history.back();
                        }else{                           
                          finish();
                        }                       
                    }

            }
            else{
                    alert("Problem bei der Server Kommunikation: "+xmlHttp.statusText);
            }
    }
}

function handleServerResponse(){
        var id;
    if(xmlHttp.readyState == 4){
        if(xmlHttp.status == 200){
            xmlResponse = xmlHttp.responseXML;
            xmlDocumentElement = xmlResponse.documentElement;   
                        hrgData = xmlDocumentElement.firstChild.data;    

                        var bla = hrgData.split(",");
                        bla[0] = bla[0].substr(1);
                        bla[bla.length-1]= bla[bla.length-1].substr(0,bla[bla.length-1].length-1);

                        var foo = [];   

                        for(var i = 0;i < bla.length;i++){

                            id = document.getElementById(i).value;
                            foo.push(id.toString());
                        }

                        if(foo.join("") != bla.join("")){
                            alert("Du elendiger Betrüger! Fang von vorne an, aber dieses mal ohne zu bescheissen!");
                            history.back();
                        }

        }
        else{
            alert("Problem bei der Server Kommunikation: "+xmlHttp.statusText);
        }
    }
}

createXMLHttpRequestObject();



function inArray(needle, haystack) {


    var length = haystack.length;
    for(var i = 0; i < length; i++) {

        if(haystack[i] == needle) return true;      
    }
    return false;
}


function array_values(){

    var values = [];
    var sichtbar = array_bilden();

    for(var i = 0; i < sichtbar.length; i++) {
        var res = document.getElementById(sichtbar[i]).value;
        values.push(res.toString());
    }

    return values;
}

function code(values){  
    var code = [];
    for(var i = 0; i < 3;i++){

        var number = Math.floor(Math.random() * values.length);

        code.push(values[number].toString());
        values.splice(number,1);        


    }   
    return code;
}


function swap(targetID) {     

    if(aktiv==1){           
            getStart();
            var values = array_values();

            var klick = document.getElementById(targetID).value;


              if(codes[number-1] == klick){                     
                      setcounter()
                      process();                    
                      var anzahl = document.getElementById("anzahl").value;
                      var max_anzahl = document.getElementById("max_anzahl").value; 
                      obj = document.getElementById(targetID); 
                      obj.style.display = "none";   
                      number++;                     
              }

            if(number == 4){
                var values = array_values();    
                    codes = code(values);
                    document.getElementById("foo").value = codes;                           
                number = 1;                 
            }                           
    }
}



function array_bilden(){

    var sichtbar = [];

    var max_anzahl = document.getElementById("max_anzahl").value;

    var strDisplay;

    for (var i = 0; i< max_anzahl; i++){
        // Falls der Brower die Methode "getComputetStyle" kennt (W3C-DOM)
      if(window.getComputedStyle){
        strDisplay = window.getComputedStyle(document.getElementById(i), "").getPropertyValue("display");    
      // Falls der Browser die Methode "currentStyle" kennt (neuere IEs)

      }else if(document.getElementById(i).currentStyle){
          strDisplay = document.getElementById(i).currentStyle.display;    

      }     
       if(strDisplay != "none") {       

                sichtbar.push(i.toString());            
        }                           
    }   

    return sichtbar;
}


function setcounter(){
    var anzahl = document.getElementById("anzahl").value;
    anzahl = anzahl -1; 
    document.getElementById("anzahl").value = anzahl;
    if(anzahl=== 0){
      aktiv = 0;
   }
}

function finish(){

    aktiv = 0;

    var time = document.getElementById("Zeit").value;
    var lvl = document.getElementById("level").value;
    document.getElementById("done_time").value = time;
    document.getElementById("done_level").value = lvl;
    document.getElementById("finish_form").submit();   

} setStart();




var javascript_countdown = function () {

        var time_left = 10; //number of seconds for countdown
        var keep_counting = 1;

        function countdown() {
        document.getElementById("start").style.display ="none";             

            if(time_left < 2) {
                keep_counting = 0;
            }
            time_left = time_left - 1;
        }
        function add_leading_zero( n ) {
            if(n.toString().length < 2) {
                return "0" + n;
            } else {
                return n;
            }
        }
        function format_output() {
            var hours, minutes, seconds;
            seconds = time_left % 60;
            minutes = Math.floor(time_left / 60) % 60;
            hours = Math.floor(time_left / 3600);   

            return seconds;
        }
        function format_output2() {
            var hours, minutes, seconds;
            seconds = VergangeneZeit % 60;
            minutes = Math.floor(VergangeneZeit / 60) % 60;
            hours = Math.floor(VergangeneZeit / 3600);  

            return seconds;
        }
        function show_time_left() {
            document.getElementById("javascript_countdown_time").innerHTML = format_output();//time_left;
        }
        function no_time_left() {
            document.getElementById("javascript_countdown_time").style.display = "none";
            document.getElementById("lvlanzeige").style.display = "none";           
            document.getElementById("start").style.display = "none";

         aktiv = 1;

            if(aktiv == 1){
                Jetzt = new Date();
                Start = Jetzt.getTime();                                                                                             
             setStart();

             if(number == 0){   
                var values = array_values();    
                    codes = code(values);
                    document.getElementById("foo").value = codes;           
                    number++;
                }
                window.setTimeout("ZeitAnzeigen()",1);
            }

        }
        return {
            count: function () {
                countdown();
                show_time_left();
            },
            timer: function () {
                javascript_countdown.count();       
                if(keep_counting) {
                    setTimeout("javascript_countdown.timer();", 1000);
                } else {
                    no_time_left();
                }
            },
            init: function (n) {
                time_left = n;
                javascript_countdown.timer();
            }
        };
    }();

function ZeitBerechnen() 
{ 
 var Jetzt2 = new Date(); 
 return((Jetzt2.getTime() - Start)/1000); 
}


function ZeitTausendstel()
{ 
 var Jetzt3 = new Date(); 
 return((Jetzt3.getTime() - Start)/10); 
}

function ZeitAnzeigen() 
{ 
 var absSekunden = Math.round(ZeitBerechnen()); 
 var tauSekunden = Math.round(ZeitTausendstel());
 var relSekunden = absSekunden % 60;
 var reltauSekunden = tauSekunden % 60;
 var absMinuten = Math.round((absSekunden-30)/60);   
 var anzSekunden ="" + ((relSekunden > 9) ? relSekunden : "0" + relSekunden);
 var anzMinuten ="" + ((absMinuten > 9) ? absMinuten : "0" + absMinuten);
 document.getElementById("Zeit").value = anzMinuten + ":" + anzSekunden + ":" + reltauSekunden;
 window.setTimeout("ZeitAnzeigen()",10); 
}
\$\endgroup\$
  • \$\begingroup\$ JSLint is a good starting point for JavaScript. It will flag up quite a few issues. In particular, it's complaining about references before definitions; and about the use of ==. \$\endgroup\$ – Peter Taylor Oct 29 '12 at 19:38
10
\$\begingroup\$
  • Don't mix German and English code. I'd highly suggest you to use only English in your code (and I'm German myself).
  • Don't mix different variable naming styles and only use variable names starting with a capital letter for constructor function which must be used with the new prefix. A good practice is to adopt the convention of the language you use, in case of JS it would be camelCase. This is a good starter for JS code convention: http://javascript.crockford.com/code.html
  • When creating the XHR object prefer XMLHttpRequest and only fallback to ActiveXObject if the native one is not defined. The latter is only necessary in IE6.
  • Indent your code properly
  • Get rid of the duplicate code in setStart and getStart. Write a single function that sends your AJAX request.
  • Never pass a string to setInterval() or setTimeout(). Doing so is as bad as using eval() and it results in unreadable and possibly insecure code as soon as you use variables since you need to insert them into the string instead of passing the actual variable. The proper solution is setInterval(function() { /* your code *) }, msecs);. The same applies to setTimeout(). If you just want to call a single function without any arguments, you can also pass the function name directly: setInterval(someFunction, msecs); (note that there are no () behind the function name)
  • Consider using a DOM abstraction library. jQuery is nice and common but there are also more lightweight alternatives (not that I'd prefer these). It will save you a lot time and is likely to make your code much nicer.
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.