Created
April 17, 2025 05:52
-
-
Save tayyebi/9d969b61a135abce637a0cad5ba59fef to your computer and use it in GitHub Desktop.
Smooth/Lazy navigation/loading (refresh-less, no post-back)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Written with assistance of AI | |
| document.dispatchEvent(new CustomEvent('contentLoaded')); | |
| $('body').append('<div id="loading" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%, -50%); background-color:#fff; padding:10px; border:1px solid #ccc; z-index:1000;">' + strings.loading + ' ... </div>'); | |
| // Function to show loading indicator | |
| function showLoading() { | |
| $('#loading').show(); | |
| } | |
| // Function to hide loading indicator | |
| function hideLoading() { | |
| $('#loading').hide(); | |
| } | |
| // Function to load page content via AJAX | |
| function loadPage(urlPath) { | |
| showLoading(); | |
| $.ajax({ | |
| url: urlPath, | |
| dataType: 'html', // Expect HTML content | |
| success: function (response) { | |
| // Parse the HTML response | |
| var parsedHTML = $(response); | |
| // Extract the content from the specific tag (e.g., #content) | |
| var newContent = parsedHTML.find('#content').html(); | |
| // Replace the existing content with the new content | |
| document.title = response.pageTitle; | |
| $('#content').html(newContent); | |
| // Trigger a custom event | |
| document.dispatchEvent(new CustomEvent('contentLoaded')); | |
| // End loading | |
| hideLoading(); | |
| // Keep history | |
| window.history.pushState({ "html": newContent, "pageTitle": response.pageTitle }, "", urlPath); | |
| }, | |
| error: function () { | |
| hideLoading(); | |
| } | |
| }); | |
| } | |
| // Handle browser back/forward button navigation | |
| window.addEventListener("popstate", function (e) { | |
| if (e.state) { | |
| document.title = e.state.pageTitle; | |
| $('#content').html(e.state.html); | |
| document.dispatchEvent(new CustomEvent('contentLoaded')); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment