Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load pages with JavaScript rather than redirect?

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

like image 767
Damen Avatar asked Jan 04 '16 10:01

Damen


People also ask

How do I load a page using JavaScript?

Approach: We can use window. location property inside the script tag to forcefully load another page in Javascript. It is a reference to a Location object that is it represents the current location of the document. We can change the URL of a window by accessing it.

Can we redirect a page using JavaScript?

In JavaScript, page redirection is simple. The window object's location object is a property. A web page can be redirected in a number of ways.


1 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.

like image 143
kaygee Avatar answered Oct 21 '22 14:10

kaygee