2
\$\begingroup\$

This is the first AJAX website I constructed. I am trying to have information generated according to the name that user types in.

It works well but I have some problem with the slow performance.
Is there anything I can do to improve the performance of this code please?

HTML:

<body background = "http://starecat.com/content/wp-content/uploads/my-code-doesnt-work-i-have-no-idea-why-my-code-works.jpg">

    <section id="fetch">
         <input type="text" placeholder="Please enter your name here" id="term" />
         <button type= "button" id="search">ENTER</button>
    </section>

    <section id="content">
        <div id = "figures">
        </div>

        <div id ="name">
            <div id = "nameBox">
            </div>
            <div id = "nameText">
            </div>
        </div>

        <div id = "clickBox">
        CLICK ME!
        </div>

        <div id = "message">        
            <div id = "messageBox">
            </div>
            <div id = "greetingText">
            </div>
            <div id = "messageText">
            </div>
        </div>
    </section>

    <section id="email">
         <input type="text" placeholder="Please enter your email here" id="emailBox" />
         <button type= "button" id="emailEnter">ENTER</button>
    </section>

</body>

jQUERY:

$(document).ready(function(){

$('#content').hide();
$('#email').hide();

$('#term').focus(function(){

    var full = $("#content section").length ? true : false; 

    if(full == false){
    $('#content').hide();
    }

});

var getFigures = function(type){

    if(type == "mf"){

        $('#figures').prepend('<img src = "images/mf.png" height = "500px" width = "500px" />');
        console.log("mf found");

    } else if (type == "mm"){

        $('#figures').prepend('<img src = "images/mm.png" height = "500px" width = "500px" />');
        console.log("mm found");

    } else if (type == "ff"){

        $('#figures').prepend('<img src = "images/ff.png" height = "500px" width = "500px" />');
        console.log("ff found");

    } else if (type == "male"){

        $('#figures').prepend('<img src = "images/male.png" height = "500px" width = "500px" />');
        console.log("male found");

    } else if (type == "female"){

        $('#figures').prepend('<img src = "images/female.png" height = "500px" width = "500px" />');
        console.log("female found");                                

    }                   

};

var displayMessage = function(message){

    console.log("box clicked");     
    $('#clickBox').hide();
    $('#message').show();

}    

var displayContent = function(){

    $('#fetch').hide();
    $('#message').hide();
    $('#content').show();

    var content = $('#term').val(); 
    content = content.toLowerCase().replace(/\b[a-z]/g, function(letter){
        return letter.toUpperCase();        
    });   

    console.log("Name entered: " + content);

    var googleApi = "https://api.com/";
    var googleKey = "googleKeyHere";
    var googleSecret = "googleSecretHere";

    var data = [];

    $.ajax({

        url: googleApi,
        headers: {
            "Authorization": "Basic " + btoa(googleKey + ":" + googleSecret)
        },
        data: data,
        dataType: 'json',
        type: 'GET',

        success: function(data) {

                var data = data || [];
                var results = data.filter(function(element, index, array){

                    if (element.name === content){

                        return (true);

                    }

                    return (false);

                    });

                    if (results[0]){

                        // user name is identified
                        console.log (results[0]);

                            var name = results[0].name;                 
                            $('#nameText').text(name);
                            console.log("Name: " + name);

                            var greeting = results[0].greeting;
                            $('#greetingText').text(greeting);
                            console.log("Greeting: " + greeting);

                            var type = results[0].type;
                            console.log("Type: " + type);

                            getFigures(type);
                            console.log("FIGURES PRINTED");                                 

                            $('#clickBox').show();          
                            $('#clickBox').click(displayMessage);

                            var message = results[0].message;
                            $('#messageText').text(message);
                            console.log("Message: " + message); 

                            return;

                    } else {

                        // user name is unidentified: new user                          
                        console.log("new user");

                            var name = content;                 
                            $('#nameText').text(name);
                            console.log("Name: " + name);               

                            var greeting = data[0].greeting;
                            $('#greetingText').text(greeting);
                            console.log("Greeting: " + greeting);

                            console.log('input#term');                      

                            $('input#term').genderApi({key: "genderAPIKeyHere"}).on('gender-found', function(e, result) {

                                if (result.accuracy >= 60) {
                                    var gender = result.gender;
                                    console.log('Gender found: ' + gender);

                                    var type = gender;
                                    console.log("Type: " + type);   

                                    getFigures(type);
                                    console.log("FIGURES PRINTED"); 

                                    if (type == gender){
                                        $('#email').show();
                                    } else if (type == item.type){
                                        $('#email').hide();
                                    }
                                }

                            }); 

                            console.log("should have printed figures yo");

                            $('#clickBox').show();          
                            $('#clickBox').click(displayMessage);

                            var message = data[0].message;
                            $('#messageText').text(message);
                            console.log("Message: " + message);     

                    }                   

            return false;

        },

        error: function(xhr,status,error) {
            console.log("ERROR: " + xhr.responseText);
            console.log("ERROR: " + status);
            console.log("ERROR: " + xhr.status);
            console.log("ERROR: " + error);
        }

    });     

};


$('#search').click(displayContent); 
$('#term').keypress(function(event){        
    if(event.which == 13){
        displayContent();
    }
    console.log("SEARCH");
});

console.log("waiting for name to be entered");

});
\$\endgroup\$
  • \$\begingroup\$ Try moving your logic out of the AJAX call by putting it into a variable/object, e.g. var data = { var firstPiece } $.ajax({ ... success: function (R) { data.firstPiece = data['name'] } }); and then doing the logic after \$\endgroup\$ – SomeRandomPerson Nov 13 '15 at 16:58
1
\$\begingroup\$

First I would suggest removing all console.log and try using the browser's debugger instead. The debugger allows you to plant breakpoints which allow you to pause running code and inspect the immediate area of the breakpoint (see variables, climb the scope, view values, run commands at that point etc.) Another quick way to do breakpoints is to use the debugger; statement. It's similar to adding console.log (thus you shouldn't forget it's there) but it pauses the code when it is reached, allowing you to inspect the code like you would have when using breakpoints.

I also notice you bind click handlers after the AJAX responds. Instead of doing this every time, try to use event delegation. It takes advantage of the fact that events emitted by elements also get intercepted by its ancestors due to "event bubbling". You'll only set the handlers once, and on an ancestor element that already exists on the page. In jQuery, you can use on

$('.ancestor-already-on-page').on('click', '.dyncamic-descendant', function(){
  // This would execute in the context of the descendant, like you normally
  // attach it to the descentant directly
});

DOM operations (retrieving elements, modifying values, changing properties etc.) are slow. You should avoid DOM operations, especially in "hot" code (code that gets executed all the time). This means every call to jQuery with a selector (like $('body') and so on) and calling methods that change the DOM is slow. If the elements don't change over the lifetime of the page, you can just fetch them once and store them in variables which you can reuse later. If DOM operations can't be avoided, then at least batch them up (do them closely to each other) so they render together rather than have them all over the code.

Also, a comparison is already a boolean by itself. Also, there's no need to write down all the possible arguments of a callback. Most IDEs will warn you of such. I read somewhere that it also affects performance, as the engine provides reference to the value, but the code isn't using it, wasting the effort.

var results = data.filter(function(element){
  return element.name === content;
});

I also notice this:

$('#term').keypress(function(event){        
  if(event.which == 13){
    displayContent();
  }
  console.log("SEARCH");
});

Instead of detecting a keypress (which can fire any time you actually press a key), wrap the input in a form, and handle the submit event of the form instead (which also fires when pressing ENTER). That way, jQuery isn't listening, creating event objects, and firing the handler every time you press a key.

\$\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.