Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save suewonjp/d86683378051a520f4e0488d0f149b06 to your computer and use it in GitHub Desktop.
Save suewonjp/d86683378051a520f4e0488d0f149b06 to your computer and use it in GitHub Desktop.
Properly using Primefaces p:poll saving network traffic
function onStartPoll() {
if ($("#fragment-group-form\\:promo-messages .ui-messages-info").is(":visible")) {
// Suspend polling while the promotion message appears (to save network traffic)
PF("poll").stop();
var timer = setInterval(function() {
if (! $("#fragment-group-form\\:promo-messages .ui-messages-info").is(":visible")) {
// The promotion message is closed; Restart polling
PF("poll").start();
clearInterval(timer);
}
}, 2000);
}
}
<h:form id="fragment-group-form">
    <p:messages id="promo-messages" escape="false" globalOnly="false" showDetail="true" closable="true"/>

    <p:poll widgetVar="poll" interval="5" autoStart="true" onstart="onStartPoll();" listener="#{pollController.test}" update="promo-messages" />    
    ...
</h:form>
package com.civilizer.web.controller;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.civilizer.web.view.*;
@ManagedBean
@ViewScoped
public final class PollController {
private static final String PROMOTION_MESSAGE_CLIENT_ID = "fragment-group-form:promo-messages";
public void test() {
ViewUtil.addMessage(PROMOTION_MESSAGE_CLIENT_ID, "Testing...", "hello", null);
}
}
@suewonjp
Copy link
Author

http://www.primefaces.org/docs/vdl/6.0/core/primefaces-p/poll.html

  • Problem Discussion
    • This will show a banner message in the browser by polling to the server at a regular interval
    • Basically it works, but not so efficient in terms of network bandwidth;
    • While the banner appears, the polling will continue ending up doing nothing useful; usually this is a waste of network traffic
  • Workaround
    • onStartPoll is called in the client when the poll request is about to start;
    • And it checks if the banner is visible and if so, it will suspend the polling to save some network bandwidth;
    • It also installs a recurring timer and in that timer callback, it will check the banner is closed by the user;
    • If it detects the banner is closed then it restarts the polling

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment