我已经为您制作了一个塞子,让您看一看,并[尽可能地使用它。您将从 到很多东西!
主要目标是使徽标文本和菜单保持不刷新,而不会在刷新页面或将内容从页面加载到另一个页面时进行裁剪。菜单状态也应从一个页面保存到另一个页面。
如果要这样做,请执行以下步骤:
完成之后,现在我们必须更改链接以使用AJAX而不是进行完全刷新:
/* we add a 'click' event handler to our menu */
document.getElementById(‘menu-menu-2’).addEventListener(‘click’, function(e) { var el = e.target;
/ then, we see if the element that was clicked is a anchor / if (el.tagName === ‘A’) { / we prevent the default functionality of the anchor (i.e redirect to the page) / e.preventDefault(); / we show our spinner, so the user can see that something is loading / spinner.classList.remove(‘hidden’);
/* and we call our AJAX function, passing a function as the callback */
ajax(el.href, function(xhr) {
/* we get our main div, and we replace its HTML to the response that came
from the AJAX request */
document.getElementById('main').innerHTML = xhr.responseText;
/* since the request was finished, we hide our spinner again */
spinner.classList.add('hidden');
});
} });
好的,现在我们的页面已经可以通过AJAX运行,并且不会重新加载我们的静态内容。
但是现在,我们看到了一些问题。例如,如果有人尝试直接通过URL打开我们的页面之一,那么他将看到没有样式的页面,而没有菜单/徽标等。那么,我们应该怎么做?
现在,我们还有几个步骤:
使用History API模拟我们的链接在页面之间有效地传输:
/* inside our ajax callback, we save the fake-redirect we made into the pushState */
ajax(el.href, function(xhr) { document.getElementById(‘main’).innerHTML = xhr.responseText;
/ save the new html, so when the user uses the back button, we can load it again / history.pushState({ html: main.innerHTML, title: el.textContent + ‘| neuegrid’ }, ‘’, el.href);
/ (…) / });
/ and outside it, we add a ‘popstate’ event handler / window.addEventListener(‘popstate’, function(e) { / so, if we’ve saved the state before, we can restore it Now / if (e.state) { document.getElementById(‘main’).innerHTML = e.state.html; document.title = e.state.title; } });
而且,当用户直接进入另一个页面(例如)时about-us
,我们需要将其重定向到index.html
,然后about-us
从那里加载页面。
因此,我们创建了一个redirect.js
文件,并在所有子页面中对其进行引用:
/* save the page that the user tried to load into the sessionStorage */
sessionStorage.setItem(‘page’, location.pathname); / and them, we redirect him to our main page / location.replace(‘/’);
然后,在我们的index.html
页面中,查看中是否有任何页面sessionStorage
,如果有的话,我们将其加载,否则,将加载我们的home
页面。
var page = sessionStorage.getItem('page') || 'home';
/ we look into the menu items, and find which has an href attribute ending with the page’s URL we wanna load / document.querySelector(‘#menu-menu-2 > li > a[href$=”’ + page + ‘“’).click();
就是这样,我们现在完成了。看看我给你做的矮人。
并尽可能地使用它,因此您将从中学到很多东西。
希望能对您有所帮助!:)
注意:仅供参考,这是我们的ajax
功能:
function ajax(url, callback, method, params) {
if (!method) method = 'GET';
var xhr = new XMLHttpRequest();
xhr.open(method, url);
if (callback) xhr.addEventListener('load', function() {
callback.call(this, xhr);
});
if (params) {
params = Object.keys(params).map(function(key) {
return encodeURIComponent(key) + '=' + encodeURIComponent(params[key]);
}).join('&');
xhr.send(params);
} else {
xhr.send();
}
}