【发布时间】:2017-06-10 06:55:56
【问题描述】:
我正在开发通知系统,但由于轮询通知,我的页面加载速度非常慢。 我的意思是非常慢,但是当我注释掉通知代码时,它运行得很顺利。这是我用于轮询通知的 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 秒并递归调用相同的函数。
请提出任何解决方案以更快地加载页面。 谢谢!
【问题讨论】:
标签: php ajax laravel push-notification notifications