javascript - Constantly check the length of an element and perform an action if it is ever 1 -
i have element on page monitoring. if @ time length equal 1, means exists on page (the user has logged out) , want prompt them popup login.
so @ moment have this:
function loginnotice() { //do prompt } keepalive(); function keepalive() { if($('.username_field').length == 1){ loginuser(); } try { settimeout(function(){keepalive();}, 10000); } catch (ex){ } }
i don't think efficient. checks every , runs prompt if need be. thing page may load , length may 1 already, or may 0. don't know @ given time can't on change.
is there way can more efficiently?
you can use mutation observer on parent/ancestor node instead, watching changes subtree
and/or childlist
.
var ancestor = $("...closest ancestor doesn't change..."); // worst case, $('body') var ob = new mutationobserver(function() { if($('.username_field').length == 1){ loginuser(); } }); ob.observe(ancestor[0], { subtree: true, // need... childlist: true // ...one of these or other });
having said that, though, doing dom query every 10 seconds isn't problem @ all; if don't need faster reactions that, current solution fine.
Comments
Post a Comment