My Goal:
Let's say I've got two webpages page1
and page2
. Now, I would like to have an animation (using css transition) to transform page1
into page2
or page2
into page1
if the user navigates from page1
to page2
or from page2
to page1
respectively.
Moreover, I would like that search engines can find both pages.
My Problems / What I've tried:
Use actually only one page
page.html
with hashes:page.html#page1
andpage.html#page2
. For example by listening for ahashchange
event the transition can be done easily.Use parameters:
page.html?content=page1
andpage.html?content=page2
. A complete reload of the page can be avoided by thepreventDefault
method orhistory.pushState
.
As far as I know, in the first solution, search engines are not going to show my pages as separate links. Also, both solutions have the following major problem: What happens if someone writes simply page.html
into the browser's address field or – even worse – page.html
appears as a link in search results? I really would like that page.html
doesn't exist at all, but that seems impossible given the above solutions.
So, the best solution I could think of so far, is having actually two pages page1.html
and page2.html
that have both exactly the same content (that is, the content of both pages combined). E.g. in page1.html
the content of page2
would have property display: none
. Now, when a user navigates from page1
to page2
, I use history.pushState
to set the new URL. While I believe this should in principle work, I'm concerned about having two identical pages or hiding large amounts of a page using display: none
as both is supposed to be bad for SEO.
Any answer that addresses at least part of my problem is very welcome! Maybe there is a way to at least prevent search engines from finding page.html
in my second solution? Or maybe there is a solution I'm completely unaware of?
CodePudding user response:
Your history.pushState
way is fine. Once a user visits page a, preload page b with JavaScript, and you can apply your CSS transitions that way. You could do something like:
(async () => {
const page2 = await fetch("/page2.html");
const text = page2.text();
// dummy event listener and selector
document.querySelector('a[href="/page2.html"]').addEventListener("click", e => {
e.preventDefault();
// apply CSS transitions by adding classes or whatever
document.documentElement.innerHTML = text;
history.pushState(null, null, "/page2.html");
});
})();
This way you don't have to change any of your HTML or CSS and no SEO will be affected. This can also improve your UX by cutting off load times to other pages, kind of like what React Router or NextJS does.