I have a table that has an href link to a picture/media file. When my page updates the image [media] flashes during the setInterval function. Everything else is fine. How would I stop this from happening?
php code
<?php
include("../lib/config.php");
$conn=mysqli_connect("$dbhost","$dbuser","$dbpass","$dbname");
$result = mysqli_query($conn, " SELECT name, message, time, media FROM message ORDER BY ID DESC");
mysqli_close($conn);
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['message'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
//echo "<td>" . $row['media'] . "</td>";
echo "<td><a href=\"" . $row['media'] . "\" target=\"_blank\" alt=\"Media not available\"> <img src=\"" . $row['media'] . "\" height=\"50\" ></a></td>";
echo "</tr>";
}
?>
js code
<script type="text/javascript">
setInterval(function(){
$.get("../pageLinks/messageOne.php" , function(result){
$("#testMessageOne").html(result);
});
}, 20000);
</script>
You would need to determine that the image(s) are loaded, prior to insertion to the DOM to prevent the flicker caused as the image(s) being rendered/downloaded by the browser.
Flicker Demo: https://jsfiddle.net/v8z5bvL2/
To do this you would need to find the image(s) in your requested content and add a load
event to trigger the insertion into the DOM once all image(s) have completed loading.
The downside is that the content will not be updated until after the images have finished loading.
Anti-Flicker Demo: https://jsfiddle.net/g7m1au40/
setInterval(function(){
$.get("../pageLinks/messageOne.php" , function(result){
var result = $(result);
var img = result.find('img');
var imgCount = img.length; //count images in the content
var imgLoaded = 0;
img.on('load', function() {
if (imgCount === 0 || imgLoaded++ === imgCount) {
//the images have finished loading, display the content.
$("#testMessageOne").html(result);
}
});
});
}, 20000);
Can you see if this fixes your problem?
setInterval(function(){
$.get("../pageLinks/messageOne.php" , function(result){
var $html = $(result);
$("#testMessageOne").replaceWith($html);
});
}, 20000);
What it does is parse the html before it's appended to the document. The jquery object turns it into valid DOM objects before it's pushed to the page.
This means the page doesn't have to do the html parsing after it's content has been cleared and should be able to update the contents much faster, and hopefully within one frame draw because it's all in one javascript call.