What are the best practices for implementing AJAX to dynamically reload content on a webpage without triggering the browser's loading spinner?
When using AJAX to dynamically reload content on a webpage, the browser's loading spinner can be triggered, giving the user a less than optimal experience. To prevent this, you can add a loading spinner that is controlled by JavaScript to show when content is being loaded, and hide it once the content has been successfully loaded.
<!DOCTYPE html>
<html>
<head>
<title>AJAX Content Loading</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#loadingSpinner {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div id="content"></div>
<div id="loadingSpinner">Loading...</div>
<script>
$(document).ready(function() {
$('#loadingSpinner').hide();
$('#content').on('click', function() {
$('#loadingSpinner').show();
$.ajax({
url: 'content.php',
success: function(data) {
$('#content').html(data);
$('#loadingSpinner').hide();
}
});
});
});
</script>
</body>
</html>