我正在处理通知系统,但由于通知轮询,我的网页加载速度很慢。 我的意思是非常慢,但是当我注释掉通知代码时,它会顺利运行。这是我的轮询通知的ajax代码:
function pollNotification() {
$.ajax({
method: 'POST',
url: urlGetNotification,
async: true,
timeout: 0,
cache: false,
data: {
_token: token
},
}).done(function (notifs) {
//my code here
}).always(pollNotification);
}
这是我的服务器端php(laravel框架)代码,用于获取通知:
public function getNotification()
{
$count=0;
$user = User::select('last_notif_timestamp')->where('id',Auth::user()->id)->get(); // fetching last timestamp when user clicked on notification
$notification = Notification::where('receiver',Auth::user()->id)->orderBy('updated_at','desc')->get(); //checking for notification in table
$prevDate = Session::get('prevDate'); //temporary variable to check when the last notification came
if($notification->count()>0) {
if ($prevDate == null || $prevDate < $notification[0]->updated_at) {
Session::set('prevDate', $notification[0]->updated_at);
$notifications = array();
foreach ($notification as $notif){
if($notif->updated_at > $user[0]->last_notif_timestamp) //Keeping track of notification counter
$count++;
$notifications[] = $notif;
}
return response()->json(['notifications'=>$notifications, 'count'=>$count],200);
}
else{
sleep(10); // Sleeping for 10 seconds for next poll
self::getNotification(); //calling function recursively
}
}
sleep(10);
self::getNotification();
}
简而言之,此代码会检查通知,如果存在新通知,则会返回带有计数值的通知。 如果没有通知,则它会休眠10秒并递归调用相同的函数。
请建议任何解决方案,以加快页面加载速度。 谢谢!
答案 0 :(得分:0)
你为什么要在php端等待?
目前你强制你的php脚本在向ajax请求发送响应之前等待,并且这个等待时间可能非常长,并且对于带有递归调用的服务器来说会占用内存。
例如,您可以使用setTimeout()在Javascript端进行简单轮询。在php方面,你可以只返回通知数组,即使它是空的(使用Javascript检查)没有任何sleep()。 这至少应该减少ajax请求的响应时间,也可能减少页面的加载时间。