Skip to content
Advertisement

How can I unload/load pages using jQuery?

Here is the things I want to achieve with jQuery.

  1. First of all, I want to save a copy of the entire page as is in a variable.
  2. I then want to replace the currently loaded page with a loading page from another html file or URL without redirecting to that page.
  3. After it has done loading, I want to replace the page back with what it originally was (the variable from step 1).

Advertisement

Answer

The question asked

  1. At it’s simplest (and this is a gross simplification that will lose state like event handlers, iframe state, shadow DOM etc.) you “save a copy” of the page’s HTML by using .html() on the root element (html or body for example).

  2. You can replace the entire top level element with fixed content from another HTML file or URL by providing the data to the same .html(data) function as well.

  3. You can restore the original content by repeating step 2 using the data you saved off in step 1.

// Step 1 - save old page
const oldPage = $('html').html();

// result of fetch() or fixed HTML from file
// const newHTML = ...

// Step 2 - load new page
$('html').html(newHTML);

// Step 3 - restore old page
$('html').html(oldPage);

What you might actually want

If you only care that the user can’t see the old page, you may want to wrap all of the UI inside a div that you can set display property to none on. You could also just overlay the new UI elements on top of the old one, possibly wrapped in a container with a solid background (to prevent old UI elements from being shown through transparent background).

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement