如何在Jquery中优化ajax请求?

时间:2022-10-13 16:01:53

I am building a mobile app using jquery mobile, jquery and php back-end. My problem is in certain pages I am sending and receiving multiple ajax requests which are visibly slowing down the performance and causes memory leaks which leads to the crashing of app in low network connections

我正在使用jquery mobile、jquery和php后端构建一个移动应用程序。我的问题是,在某些页面中,我正在发送和接收多个ajax请求,这明显降低了性能,并导致内存泄漏,导致应用程序在低网络连接中崩溃

What are the possible ways of optimizing the ajax requests?

优化ajax请求的可能方法是什么?

note:- I am sending some ajax requests periodically(like once in a second) Some ajax are sent based on events

注意:-我定期发送一些ajax请求(比如每秒一次),一些ajax是基于事件发送的

8 个解决方案

#1


20  

First off, correctly written Ajax code does not leak memory. So, if you actually have a leak, that is likely caused by incorrectly written code, not by using Ajax.

首先,正确编写的Ajax代码不会泄漏内存。因此,如果您确实有泄漏,这很可能是由于编写错误的代码造成的,而不是使用Ajax造成的。

Then, there are a number of optimizations you can consider.

然后,您可以考虑一些优化。

  1. Combine multiple requests to your server into one larger request. This saves roundtrips to the server, saves bandwidth, saves battery and increases performance.

    将对服务器的多个请求合并为一个较大的请求。这样可以节省到服务器的往返时间,节省带宽,节省电池,提高性能。

  2. Don't poll every second. Be smarter about how often you poll your server.

    不调查每一秒。在轮询服务器的频率上要更聪明。

  3. Lengthen the polling interval to vary it based on likely activity, switch to "long polling" or switch to a webSocket so you can do server push with no polling.

    延长轮询间隔,根据可能的活动更改它,切换到“长轮询”或切换到webSocket,这样您可以在不轮询的情况下执行服务器推送。

  4. Analyze what is causing excessive memory consumption and fix bugs or redesign to curtail that. There is no reason that lots of Ajax calls should "leak" memory. It will chew up battery life, but need not leak memory if coded correctly.

    分析是什么导致了过度的内存消耗,并修复bug或重新设计以减少内存消耗。没有理由说大量的Ajax调用应该“泄漏”内存。它将消耗电池寿命,但如果编码正确,则不需要泄漏内存。

Oh, and don't hesitate to pull up some high scale social web apps that already exist, open the debugger, switch to the network tab and study the heck out of what they are doing. You may as well learn from high scale apps that already have solved this issue.

哦,不要犹豫,要打开一些已经存在的高级社交网络应用程序,打开调试器,切换到网络标签,学习他们正在做的事情。您不妨从已经解决了这个问题的大型应用程序中学习。

#2


2  

Long Polling Is Better Than Polling

长轮询优于轮询

If you poll in a set interval it is probably better if you set a timeout on server-side and wait to return a message until a given number of loops. This makes especially sense for SPA. However if you poll, you should increase the time intervall with every empty response you get.

如果您在一个设置的间隔内轮询,那么最好在服务器端设置超时,并等待返回消息,直到给定的循环数。这对SPA尤其有意义。然而,如果你投票,你应该增加你得到的每一个空反应的时间间隔。

Group Requests By Events, Not By Entity

按事件而不是实体分组请求

Let's say you poll every 10 seconds, to retrieve new messages. Moreover you poll every 10 seconds to retrieve more notifications. Instead of doing two requests you should only do one ajax request and return one big json response, which you then use to modify DOM elements on the client side.

假设您每10秒轮询一次,以获取新的消息。此外,您每10秒轮询一次以获取更多的通知。您应该只执行一个ajax请求并返回一个大型json响应,而不是执行两个请求,然后使用这个响应来修改客户端的DOM元素。

Use Server-Sent Events Or Sockets If Possible

如果可能的话,使用服务器发送的事件或套接字

Sockets or Server-Sent Events will result in much less requests and will only notify you if something actually happened on the server side. Here is a good comparison.

套接字或服务器发送的事件将导致更少的请求,并且只有在服务器端确实发生了一些事情时才通知您。这里有一个很好的比较。

#3


1  

Also, If you want to make a chat server or send fast messages to the server, you should use webSockets like socket.io .

另外,如果您想要创建一个聊天服务器或向服务器发送快速消息,您应该使用像socket这样的webSockets。io。

#4


1  

Here are few things you can do

这里有一些你能做的事情

Firstly

首先

  • Get rid of all the memory leaks. Put your application in to a sandbox and give it the toughest time you can to record any memory leaks. Investigate them and correct your code.
  • 清除所有内存泄漏。将应用程序放在沙箱中,并在记录任何内存泄漏时给它最困难的时间。调查他们并改正你的代码。

Then

然后

  • Reduce the number of requests. Carefully research on the best thresholds in your application and only trigger your requests at theses. Try to batch your requests and put them in to a single request whenever possible.

    减少请求的数量。仔细研究应用程序中的最佳阈值,只在论文中触发您的请求。尝试将您的请求批量处理,并尽可能地将它们放入到单个请求中。

  • Use GET requests whenever possible. They are comparably simple and would act fast. This step is important for an application which triggers a lot of requests in its operation.

    尽可能使用GET请求。它们相当简单,而且行动迅速。对于在其操作中触发大量请求的应用程序来说,这一步非常重要。

  • Choose the data format carefully. It could be plain text, JSON or XML. Figure out the one that have the lowest impact on your application and switch to that appropriately. Configure your server to use data compression if possible.

    仔细选择数据格式。它可以是纯文本、JSON或XML。找出对您的应用程序影响最小的一个,并适当地切换到它。如果可能,配置服务器使用数据压缩。

  • Optimize the server. Use proper Expire or Cache-Control headers for the content being servers. Use ETags if possible.

    优化服务器。对服务器内容使用适当的过期或缓存控制头。如果可能的话,使用etag。

  • Try putting your content on a CDN. This may place the resources in a geographically closer location to the user and make your application work faster.

    试着把你的内容放到CDN上。这可能会将资源放置在离用户更近的地理位置,并使应用程序工作得更快。

#5


1  

There are mainly 3 steps for optimization (minimize) jQuery AJAX calls:

优化(最小化)jQuery AJAX调用主要有3个步骤:

  • Either pass the done callback function as an argument when calling your function
  • 在调用函数时,可以将done回调函数作为参数传递
  • return the jqXhr object from the function, and assign the done callback
  • 从函数中返回jqXhr对象,并分配done回调
  • Alternatively switch to using jQuery.ajax() instead, and pass the entire options object
  • 或者切换到使用jQuery.ajax(),并传递整个options对象

Please refer this link : How to optimize (minimize) jQuery AJAX calls

请参考这个链接:如何优化(最小化)jQuery AJAX调用

#6


0  

You can use the cache feature of the Ajax call for this that helps you to get all data in first during the request and stored in cache and from next time no Ajax request happened and data manipulation done using cached data only.

您可以使用Ajax调用的缓存特性,它可以帮助您在请求期间首先获取所有数据并存储在缓存中,并且从下一次不会发生Ajax请求,并且只使用缓存数据进行数据操作。

Also, you can only optimize Ajax call request and response time by reducing the amount of data requested and sent while Ajax call. This can be done only by removing unwanted data during Ajax call.

此外,您只能通过减少Ajax调用时请求和发送的数据量来优化Ajax调用请求和响应时间。这只能通过在Ajax调用期间删除不需要的数据来实现。

Other than that, all optimization depends on code and database logic. To increase performance and reduce app crashing, optimized code and database logic helps you.

除此之外,所有的优化都依赖于代码和数据库逻辑。为了提高性能和减少应用程序崩溃,优化的代码和数据库逻辑可以帮助您。

#7


0  

  1. Create variable with ajax callback and use it
  2. 使用ajax回调创建变量并使用它
  3. Each second you create new xhr request instance, that will be in memory until done callback executes.Better way is to create new ajax request on previous ajax complete, that means you will have only one xhr request instance at time.
  4. 每一秒钟都要创建新的xhr请求实例,该实例将保存在内存中,直到执行回调。更好的方法是在以前的ajax complete上创建新的ajax请求,这意味着每次只有一个xhr请求实例。
  5. After data send to server, clean your object data, for example:

    数据发送到服务器后,清理对象数据,例如:

    array.length = 0; object = null; image.src = ""; file = null;

    数组中。长度= 0;对象=零;的形象。src = " ";文件=零;

#8


0  

As @jfriend00 said, Ajax requests don't generate memory leaks issues...

正如@jfriend00所说,Ajax请求不会产生内存泄漏问题……

this is what your code probably do!

这就是代码可能做的事情!

The best way to do what you need is to open a Socket Layer with your Data Layer Service, so, instead of a polling, you can be notified when a domain-model change occurs.

完成所需工作的最佳方法是使用数据层服务打开套接字层,因此,当发生域模型更改时,可以通知您而不是轮询。

Checkout at Socket.io...

付款在socket . io…

If you don't want to implement a Socket Layer, I think there aren't many way to increase performances...

如果您不想实现套接字层,我认为没有很多方法可以提高性能……

One thing that, in addition - of course - to the code improvement operations (refactoring, ecc.), in my opinion, you can do is to implement a "Tail Management System"...

在我看来,除了代码改进操作(重构,ecc)之外,您还可以实现一个“尾部管理系统”……

  • Study how Promises work (es6, jQuery, Q, bluebird)
  • 研究承诺如何工作(es6, jQuery, Q, bluebird)
  • Create A QueueService, a simple Javascript Class that knows how to serialize all (Ajax) tasks (promises);
  • 创建QueueService,一个简单的Javascript类,它知道如何序列化所有(Ajax)任务(承诺);
  • Interpose the QueueService between Controllers and Data Layer Access Services
  • 在控制器和数据层访问服务之间插入QueueService
  • Implement a simple lightweight CacheSystem that prevents unnecessary AjaxRequests!
  • 实现一个简单的轻量级CacheSystem,防止不必要的ajaxrequest !

#1


20  

First off, correctly written Ajax code does not leak memory. So, if you actually have a leak, that is likely caused by incorrectly written code, not by using Ajax.

首先,正确编写的Ajax代码不会泄漏内存。因此,如果您确实有泄漏,这很可能是由于编写错误的代码造成的,而不是使用Ajax造成的。

Then, there are a number of optimizations you can consider.

然后,您可以考虑一些优化。

  1. Combine multiple requests to your server into one larger request. This saves roundtrips to the server, saves bandwidth, saves battery and increases performance.

    将对服务器的多个请求合并为一个较大的请求。这样可以节省到服务器的往返时间,节省带宽,节省电池,提高性能。

  2. Don't poll every second. Be smarter about how often you poll your server.

    不调查每一秒。在轮询服务器的频率上要更聪明。

  3. Lengthen the polling interval to vary it based on likely activity, switch to "long polling" or switch to a webSocket so you can do server push with no polling.

    延长轮询间隔,根据可能的活动更改它,切换到“长轮询”或切换到webSocket,这样您可以在不轮询的情况下执行服务器推送。

  4. Analyze what is causing excessive memory consumption and fix bugs or redesign to curtail that. There is no reason that lots of Ajax calls should "leak" memory. It will chew up battery life, but need not leak memory if coded correctly.

    分析是什么导致了过度的内存消耗,并修复bug或重新设计以减少内存消耗。没有理由说大量的Ajax调用应该“泄漏”内存。它将消耗电池寿命,但如果编码正确,则不需要泄漏内存。

Oh, and don't hesitate to pull up some high scale social web apps that already exist, open the debugger, switch to the network tab and study the heck out of what they are doing. You may as well learn from high scale apps that already have solved this issue.

哦,不要犹豫,要打开一些已经存在的高级社交网络应用程序,打开调试器,切换到网络标签,学习他们正在做的事情。您不妨从已经解决了这个问题的大型应用程序中学习。

#2


2  

Long Polling Is Better Than Polling

长轮询优于轮询

If you poll in a set interval it is probably better if you set a timeout on server-side and wait to return a message until a given number of loops. This makes especially sense for SPA. However if you poll, you should increase the time intervall with every empty response you get.

如果您在一个设置的间隔内轮询,那么最好在服务器端设置超时,并等待返回消息,直到给定的循环数。这对SPA尤其有意义。然而,如果你投票,你应该增加你得到的每一个空反应的时间间隔。

Group Requests By Events, Not By Entity

按事件而不是实体分组请求

Let's say you poll every 10 seconds, to retrieve new messages. Moreover you poll every 10 seconds to retrieve more notifications. Instead of doing two requests you should only do one ajax request and return one big json response, which you then use to modify DOM elements on the client side.

假设您每10秒轮询一次,以获取新的消息。此外,您每10秒轮询一次以获取更多的通知。您应该只执行一个ajax请求并返回一个大型json响应,而不是执行两个请求,然后使用这个响应来修改客户端的DOM元素。

Use Server-Sent Events Or Sockets If Possible

如果可能的话,使用服务器发送的事件或套接字

Sockets or Server-Sent Events will result in much less requests and will only notify you if something actually happened on the server side. Here is a good comparison.

套接字或服务器发送的事件将导致更少的请求,并且只有在服务器端确实发生了一些事情时才通知您。这里有一个很好的比较。

#3


1  

Also, If you want to make a chat server or send fast messages to the server, you should use webSockets like socket.io .

另外,如果您想要创建一个聊天服务器或向服务器发送快速消息,您应该使用像socket这样的webSockets。io。

#4


1  

Here are few things you can do

这里有一些你能做的事情

Firstly

首先

  • Get rid of all the memory leaks. Put your application in to a sandbox and give it the toughest time you can to record any memory leaks. Investigate them and correct your code.
  • 清除所有内存泄漏。将应用程序放在沙箱中,并在记录任何内存泄漏时给它最困难的时间。调查他们并改正你的代码。

Then

然后

  • Reduce the number of requests. Carefully research on the best thresholds in your application and only trigger your requests at theses. Try to batch your requests and put them in to a single request whenever possible.

    减少请求的数量。仔细研究应用程序中的最佳阈值,只在论文中触发您的请求。尝试将您的请求批量处理,并尽可能地将它们放入到单个请求中。

  • Use GET requests whenever possible. They are comparably simple and would act fast. This step is important for an application which triggers a lot of requests in its operation.

    尽可能使用GET请求。它们相当简单,而且行动迅速。对于在其操作中触发大量请求的应用程序来说,这一步非常重要。

  • Choose the data format carefully. It could be plain text, JSON or XML. Figure out the one that have the lowest impact on your application and switch to that appropriately. Configure your server to use data compression if possible.

    仔细选择数据格式。它可以是纯文本、JSON或XML。找出对您的应用程序影响最小的一个,并适当地切换到它。如果可能,配置服务器使用数据压缩。

  • Optimize the server. Use proper Expire or Cache-Control headers for the content being servers. Use ETags if possible.

    优化服务器。对服务器内容使用适当的过期或缓存控制头。如果可能的话,使用etag。

  • Try putting your content on a CDN. This may place the resources in a geographically closer location to the user and make your application work faster.

    试着把你的内容放到CDN上。这可能会将资源放置在离用户更近的地理位置,并使应用程序工作得更快。

#5


1  

There are mainly 3 steps for optimization (minimize) jQuery AJAX calls:

优化(最小化)jQuery AJAX调用主要有3个步骤:

  • Either pass the done callback function as an argument when calling your function
  • 在调用函数时,可以将done回调函数作为参数传递
  • return the jqXhr object from the function, and assign the done callback
  • 从函数中返回jqXhr对象,并分配done回调
  • Alternatively switch to using jQuery.ajax() instead, and pass the entire options object
  • 或者切换到使用jQuery.ajax(),并传递整个options对象

Please refer this link : How to optimize (minimize) jQuery AJAX calls

请参考这个链接:如何优化(最小化)jQuery AJAX调用

#6


0  

You can use the cache feature of the Ajax call for this that helps you to get all data in first during the request and stored in cache and from next time no Ajax request happened and data manipulation done using cached data only.

您可以使用Ajax调用的缓存特性,它可以帮助您在请求期间首先获取所有数据并存储在缓存中,并且从下一次不会发生Ajax请求,并且只使用缓存数据进行数据操作。

Also, you can only optimize Ajax call request and response time by reducing the amount of data requested and sent while Ajax call. This can be done only by removing unwanted data during Ajax call.

此外,您只能通过减少Ajax调用时请求和发送的数据量来优化Ajax调用请求和响应时间。这只能通过在Ajax调用期间删除不需要的数据来实现。

Other than that, all optimization depends on code and database logic. To increase performance and reduce app crashing, optimized code and database logic helps you.

除此之外,所有的优化都依赖于代码和数据库逻辑。为了提高性能和减少应用程序崩溃,优化的代码和数据库逻辑可以帮助您。

#7


0  

  1. Create variable with ajax callback and use it
  2. 使用ajax回调创建变量并使用它
  3. Each second you create new xhr request instance, that will be in memory until done callback executes.Better way is to create new ajax request on previous ajax complete, that means you will have only one xhr request instance at time.
  4. 每一秒钟都要创建新的xhr请求实例,该实例将保存在内存中,直到执行回调。更好的方法是在以前的ajax complete上创建新的ajax请求,这意味着每次只有一个xhr请求实例。
  5. After data send to server, clean your object data, for example:

    数据发送到服务器后,清理对象数据,例如:

    array.length = 0; object = null; image.src = ""; file = null;

    数组中。长度= 0;对象=零;的形象。src = " ";文件=零;

#8


0  

As @jfriend00 said, Ajax requests don't generate memory leaks issues...

正如@jfriend00所说,Ajax请求不会产生内存泄漏问题……

this is what your code probably do!

这就是代码可能做的事情!

The best way to do what you need is to open a Socket Layer with your Data Layer Service, so, instead of a polling, you can be notified when a domain-model change occurs.

完成所需工作的最佳方法是使用数据层服务打开套接字层,因此,当发生域模型更改时,可以通知您而不是轮询。

Checkout at Socket.io...

付款在socket . io…

If you don't want to implement a Socket Layer, I think there aren't many way to increase performances...

如果您不想实现套接字层,我认为没有很多方法可以提高性能……

One thing that, in addition - of course - to the code improvement operations (refactoring, ecc.), in my opinion, you can do is to implement a "Tail Management System"...

在我看来,除了代码改进操作(重构,ecc)之外,您还可以实现一个“尾部管理系统”……

  • Study how Promises work (es6, jQuery, Q, bluebird)
  • 研究承诺如何工作(es6, jQuery, Q, bluebird)
  • Create A QueueService, a simple Javascript Class that knows how to serialize all (Ajax) tasks (promises);
  • 创建QueueService,一个简单的Javascript类,它知道如何序列化所有(Ajax)任务(承诺);
  • Interpose the QueueService between Controllers and Data Layer Access Services
  • 在控制器和数据层访问服务之间插入QueueService
  • Implement a simple lightweight CacheSystem that prevents unnecessary AjaxRequests!
  • 实现一个简单的轻量级CacheSystem,防止不必要的ajaxrequest !