如何优化jquery ajax聊天?

时间:2019-01-16 08:26:42

标签: jquery ajax performance

我正在尝试建立自己的jquery ajax聊天,当消息像Facebook一样时,它是实时通知。该计划是每5秒调用一次ajax请求,最后我的计划按我的预期工作正常。 但是发送消息超过5次后,我的应用程序性能出现问题。当用户在输入框中输入消息时,浏览器将变得非常慢。 至少我在做以下事情:

//function to updating html element when new message comes (DOM operation)
function refresh_messanger(){

                $(".dialogdiv").remove();
                var y=get_update_message_in_messanger();

                for(var i=0; i<= y.length-1; i++){
                var message=y[i].message_content;
                var message_date=y[i].message_date;
                var src="";
                if(y[i].photo_profile=='{{session("session_photo_profile")}}'){
                    src="{{url('uploads/image').'/'.session('session_login')['app_user_id'].'/'.session('session_photo_profile')}}";
                }else{
                    src="{{url('uploads/image')}}/"+y[i].message_from+'/'+y[i].photo_profile;
                }
                var message_class="";
                if(i==0){
                    message_class="text-bold"
                }else{
                    message_class="text";
                }
                var messagehtml=['<div class="itemdiv dialogdiv">',
                            '<div class="user">',
                                '<img alt="" height="60" width="40" src="'+src+'">',                                
                            '</div>',
                            '<div class="body">',
                                '<div class="time">',
                                    '<i class="ace-icon fa fa-clock-o"></i>',
                                    '<span class="blue">'+message_date+'</span>',
                                '</div>',

                                '<div class="name">',
                                    '<a href="#"></a>',
                                '</div>',
                                '<div class="'+message_class+'">'+message+'</div>',
                                '<div class="tools">',
                                    '<a href="#" class="btn btn-minier btn-info">',
                                        '<i class="icon-only ace-icon fa fa-trash"></i>',
                                    '</a>',
                                '</div>',
                            '</div>',
                        '</div>'].join('\n');
                        //alert(messagehtml);
                        $("#message_wall").append(messagehtml);     
                }

            }

  //display number of messsage realtime
            function get_all_notif_message(){
                var number_of_messages=0;
                var message_from   ="{{$message_from}}";
                var message_to     ="{{$message_to}}";
                var message_url    ="{{url('messanger/realtime/message_notification')}}"+"/"+message_from+"/"+message_to;
                $.ajax({
                    url        :message_url,
                    contentType:"application/json",
                    type       :"get",
                    async      :false,
                    success: function (response) {
                      var data=JSON.parse(response);
                      //$("#total_message").val(data.number_of_messages)
                      //alert(data.number_of_messages)
                      number_of_messages=data.number_of_messages;
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                       console.log(textStatus, errorThrown);
                    }


                });
                return number_of_messages;
            }

//function to handle DOM operatioin base on old number total  
function listen_crud(){                 
  var uptodate_message=get_all_notif_message();         
  $("#uptodate_massage").val(get_all_notif_message());          
  if($("#total_message").val() < uptodate_message){
  //alert("new message received")
`var audio = new Audio('{{url("assets/sound/inquisitiveness.mp3")}}');              
audio.play();           
$("#total_message").val(uptodate_message);              
refresh_messanger();
`var objDiv =` `document.getElementById("message_container");`                              
objDiv.scrollTo(x-coord, y-coord);                      
 }      
} 
//first program running
setInterval(listen_crud,5000);

https://pastebin.com/6rhpwCir HTML View related to .dialogdiv class"

请给我您的建议。

1 个答案:

答案 0 :(得分:0)

@Alimin设置async: false使其阻止输入/输出。这意味着在执行ajax期间,整个浏览器将不得不冻结,直到返回作为响应(成功或错误)为止。您说过,您不想在成功函数中做任何事情-这只是结构代码。 $.ajax()返回承诺。您可以使用async/ await并像同步代码一样编写它-更加简洁。

说实话,它的错误设计每隔几秒钟就会将ajax称为“实时”。您可以使用websockets。 Socket IO就是一个例子。真的很简单轻巧。您可以启动Node服务器运行Socket IO,并单独安装Laravel服务器。

这是最简单的:

客户Js-在Laravel中

<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<script>
  $(function () {
    var socket = io('localhost:3000'); // connect to socket io server
    $('form').submit(function(e){
      e.preventDefault(); // prevents page reloading
      socket.emit('chat message', $('#m').val()); //replace with your msg input
      $('#m').val(''); //replace with your msg input
      return false;
    });

    socket.on('chat message', function(msg){
      console.log(msg); //receive message from node js
     });

  });
</script>

节点Js

var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.get('/', function(req, res){
  res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket){
  console.log('a user connected');
});

http.listen(3000, function(){
  console.log('listening on *:3000');
});

io.on('connection', function(socket){
  socket.on('chat message', function(msg){ //listen for 'chat message' event
    io.emit('chat message', msg); //send data to clients
    console.log('message: ' + msg);
  });
});

更新17/01/2019:

我已删除async: false,因此浏览器不起作用。因此,要使用从ajax请求返回的数据,请使用async/ await。更加整洁。

//function to updating html element when new message comes (DOM operation)
function refresh_messanger(){

$(".dialogdiv").remove();
    var y=get_update_message_in_messanger();

    for(var i=0; i<= y.length-1; i++){
        var message=y[i].message_content;
        var message_date=y[i].message_date;
        var src="";
        if(y[i].photo_profile=='{{session("session_photo_profile")}}'){
            src="{{url('uploads/image').'/'.session('session_login')['app_user_id'].'/'.session('session_photo_profile')}}";
        }else{
            src="{{url('uploads/image')}}/"+y[i].message_from+'/'+y[i].photo_profile;
        }
        var message_class="";
        if(i==0){
            message_class="text-bold"
        }else{
            message_class="text";
        }
        var messagehtml=['<div class="itemdiv dialogdiv">',
                    '<div class="user">',
                        '<img alt="" height="60" width="40" src="'+src+'">',                                
                    '</div>',
                    '<div class="body">',
                        '<div class="time">',
                            '<i class="ace-icon fa fa-clock-o"></i>',
                            '<span class="blue">'+message_date+'</span>',
                        '</div>',

                        '<div class="name">',
                            '<a href="#"></a>',
                        '</div>',
                        '<div class="'+message_class+'">'+message+'</div>',
                        '<div class="tools">',
                            '<a href="#" class="btn btn-minier btn-info">',
                                '<i class="icon-only ace-icon fa fa-trash"></i>',
                            '</a>',
                        '</div>',
                    '</div>',
                '</div>'].join('\n');
                //alert(messagehtml);
                $("#message_wall").append(messagehtml);     
    }

}

    //display number of messsage realtime
    async function get_all_notif_message(){
        var number_of_messages=0;
        var message_from   ="{{$message_from}}";
        var message_to     ="{{$message_to}}";
        var message_url    ="{{url('messanger/realtime/message_notification')}}"+"/"+message_from+"/"+message_to;

        let ajax_res;

        ajax_res = await $.ajax({
            url        :message_url,
            contentType:"application/json",
            type       :"get",    
        });

        let data = JSON.parse(ajax_res);
        return data.number_of_messages;
    }

    //function to handle DOM operatioin base on old number total  
    async function listen_crud(){ 
        let uptodate_message;


        try {
            uptodate_message= await get_all_notif_message();    
        } catch (error) {
            alert("Error");
            console.log(error);
            return;
        }                

        $("#uptodate_massage").val(uptodate_message);
        if($("#total_message").val() < uptodate_message){
            //alert("new message received")
            var audio = new Audio('{{url("assets/sound/inquisitiveness.mp3")}}');              
            audio.play();           
            $("#total_message").val(uptodate_message);              
            refresh_messanger();
            var objDiv = document.getElementById("message_container");                              
            objDiv.scrollTo(x-coord, y-coord);                      
        }      

        setTimeout(listen_crud, 5000);

    } 


    //first program running
    setTimeout(listen_crud, 5000);

资源:

https://socket.io/get-started/chat/

https://javascript.info/async-await