Home » Php » php – How to load pages with JavaScript rather than redirect?

php – How to load pages with JavaScript rather than redirect?

Posted by: admin July 12, 2020 Leave a comment

Questions:

The best example of what I’m trying to do is YouTube’s navigation system. If you click on a link to a video a red bar at the top of the page appears indicating how much of the requested page has loaded. When the requested page is finished loading it instantly replaces the contents of the previous page and the video starts to load. Several things are happening to make this as seamless as possible.

  • The URL is modified to match the new page.
  • No redirect(This is hard to explain).
  • The new page is added to the History.
  • Back and Forth navigation works seamlessly.

I modified the URL with:

window.history.pushState("object or string", "Title", "/new-url");

I attempted to load the requested page with:

$.("html").load("newPage.php", function(){});

This would replace the entire previous page’s code with the new pages code. Several issues with this:

  • Back and forth navigation works with the URL, but an event handler must detect this and load the proper page. I used this:

    $(window).on('popstate', function() {
        $('html').load("../"+window.location.pathname, {page:"account"});
    });
    
  • Using $.load() can’t(shouldn’t) load any new scripts tags script tags because Synchronous XMLHttpRequest on the main thread is deprecated

What I’d like to be able to do:

  • Seamlessly load a page without a redirect using JQuery and AJAX
  • Have that new page be able to have new script and PHP tags(PHP might be impossible, and I might have to use AJAX to replicate this).

Sources:

Updating address bar with new URL without hash or reloading the page

Load HTML page dynamically into div with jQuery

JS or Jquery browser back button click detector

Synchronous XMLHttpRequest on the main thread is deprecated

How to&Answers:

This following post might help you.

Curious about the new way YouTube is loading pages

You can check if a js library called history.js can help you achieve what you need.

Answer:

The history.js library does all the hard work of dealing with history and I just have to worry about the navigation, which was easy. All I need to do is have all the scripts loaded on the initial load of the page(when the user first comes to the site). Then when they are “redirected” the page body is replaced with the correct page using $("body").load("pageToBeLoaded.php",pageToBeLoaded()). The pageToBeLoaded() function is called on completion, and it handles all the fun stuff for the new page.