I have a button to pull some data from backend. But the length of the data is uncertain and the time to load is also uncertain.
This will generate high CLS penalty. Is there anyway to avoid this?
var stHandler = 0;
$('#render').click(function(){
clearTimeout(stHandler);
$('#result').html('loading...');
// [Simulate the server response time]
// CLS will not be penalized if the everything happens in 100ms,
// but most of the case, the server will return the data longer than that
stHandler = setTimeout(function(){
$('#result').html(fakeResultBuilder);
}, 500 + Math.random()*1000);
})
// [Simulate the real-world condition]
// Every time you load this content, the height will be different.
function fakeResultBuilder(){
var html = '';
for (var i=0; i<Math.random()*100; i++) {
html += '<div class="block"></div>';
}
return html;
}
button {cursor:pointer}
.block {height:10px; background:#f00; width:20px; margin:5px}
#result {border:1px solid #999}
footer {margin-top:1em}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<button id="render">Render</button>
</div>
<h2>Result:</h2>
<div id="result"></div>
<footer>Page Footer - will have huge CLS sometimes</footer>