mootools_MooTools历史记录插件

mootools

One of the reasons I love AJAX technology so much is because it allows us to avoid unnecessary page loads.  Why download the header, footer, and other static data multiple times if that specific data never changes?  It's a waste of time, processing, and bandwidth.  Unfortunately, at this point in the web, constant refreshes are the norm -- but they don't have to be.  Christoph Pojer, a MooTools Core Developer, has added History to his PojerTools PowerTools library.  History replaces traditional same-site URL loading by providing a method to catch link clicks, load page content via AJAX (Mootools' Request.HTML class), modify the document's location object to keep "history" records, and re-evaluate content links to allow developers to create a fast, efficient one-page website.

我之所以非常喜欢AJAX技术,原因之一是因为它使我们避免了不必要的页面加载。 如果特定数据永不更改,为什么还要多次下载页眉,页脚和其他静态数据? 这浪费时间,处理和带宽。 不幸的是,在网络的这一点上,经常刷新是常态-但不一定必须如此。 MooTools核心开发人员Christoph Pojer将历史添加到他的 Pojer工具 PowerTools库。 历史记录通过提供一种方法来捕获链接单击,通过AJAX加载页面内容(Mootools的Request.HTML类),修改文档的位置对象以保留“历史记录”并重新评估内容链接,从而取代了传统的同一站点URL加载。允许开发人员创建快速,高效的一页网站。

The tradition method of dynamic history/"back button" management has always been hash-based JavaScript technology.  Newer technology, including HTML5's window.onpopstate and history.pushState methods, allow for more reliable methods for managing history.  MooTools' History plugin supports modern and legacy methods for history management.  Let me show you how to quickly implement the MooTools History plugin.

动态历史记录/“后退按钮”管理的传统方法一直是基于哈希JavaScript技术。 包括HTML5的window.onpopstatehistory.pushState方法在内较新技术允许使用更可靠的方法来管理历史记录。 MooTools的“历史记录”插件支持现代和旧式历史记录管理方法。 让我向您展示如何快速实现MooTools历史插件。

HTML结构 (HTML Structure)

The History plugin doesn't require any HTML structure adjustments but at least one designated content should be identified; you can, of course, have as many content areas as you like, but you'll most likely need multiple AJAX requests to retrieve their content, unless you use a Request.JSON request to retrieve content for multiple areas of the page. For this simple demo, we'll define a header, footer, and menu, and content area:

历史记录插件不需要任何HTML结构调整,但至少应标识一个指定的内容; 您当然可以拥有尽可能多的内容区域,但是您很可能需要多个AJAX请求来检索其内容,除非您使用Request.JSON请求来检索页面多个区域的内容。 对于这个简单的演示,我们将定义一个页眉,页脚,菜单和内容区域:


<div id="body">
	
	<!-- header -->
	<header>
		<a href="/" data-noxhr>David Walsh Blog</a> 

The content area is the only area which will have its content change. The page should load as usual

内容区域是唯一会更改其内容的区域。 该页面应照常加载

MooTools JavaScript (The MooTools JavaScript)

Assuming that the MooTools History plugin has been included in the page, there are a few functions that should be created upon domready.  The first is a method which will perform the request for content when a link is clicked:

假设页面中已包含MooTools历史记录插件 ,则应在domready上创建一些功能。 第一种是单击链接时将执行对内容的请求的方法:


// Content holder (all content placed within this element)
var contentHolder = document.id("contentHolder");

// Create a Request object which will be reused when links are clicked
var request = new Request.HTML({
	onSuccess: function(nodeTree,elements,html) {
		// Set the content into the content holder
		contentHolder.set("html",html);
		// Execute directions that should be executed whenever a page changes
		onPageUpdate();
	}
});

// Create a function that loads the page content
var loadPage = function(url) {
	// Make a HTML request to get the content for this page
	request.send({ url: url });
};


The next step is creating a method (which is theoretically option, but you'll usually want to do something once content has loaded) which will execute every time content is received:

下一步是创建一个方法(理论上是可选的,但是通常需要在内容加载后做一些事情) ,该方法将在每次接收到内容时执行:


// Function that will execute whenever a page gets changed
var onPageUpdate = function() {
	
	// Do whatever you'd like here!  
	
	// Possibly manually record a Google Analytics page view?
	
};


History doesn't request that you do anything when content is received, but you'll likely want to do something. Why manually record a page view within Google Analytics?

历史记录不要求您在收到内容时做任何事情,但是您可能会想做某事。 为什么要在Google Analytics(分析)中手动记录网页浏览

This next piece is important in turning links to static pages into AJAX-ified History triggers. Just one big Element.Delegation event delegation call will do the work for not just the initial page load, but every History AJAX load after that:

下一部分对于将静态页面的链接转换为AJAX化的历史记录触发器非常重要。 只需一个大的Element.Delegation事件委托调用就可以完成初始页面加载的工作,还可以完成之后的每个History AJAX加载:


// The listener that manages all clicks
var listener = function(evt){
	evt.preventDefault(); // Prevent following the URL
	History.push(this.get('href')); // Push the new URL into History
};

// Add event delegation to add clicks.  Both of these work:
//document.body.addEvent("click:relay(a:not([href=#]):not([href^=http://]):not([data-noxhr]))",listener);
document.body.addEvent("click:relay(a:not([href=#],[href^=http://],[data-noxhr]))",listener);

When any same-site, non-hashed link is clicked, the listener method stops the event and pushes the new URL into History, changing the address bar and managing back/forward button click.

单击任何未隐藏的相同站点的链接时,侦听器方法将停止事件并将新URL推送到“历史记录”中,从而更改地址栏并管理后退/前进按钮的单击。

A back function is also created so that we can provide a "back" link and a "forward" link to travel back and forward in page history, if we choose to use it:

还创建了back功能,以便我们提供“后退”链接和“前进”链接以在页面历史记录中来回移动(如果我们选择使用它):


// Listener for the "Back" link
var back = function(evt){
	evt.preventDefault();
	History.back(); // Go back
};

// Listener for the "Forward" link
var forward = function(evt){
	evt.preventDefault();
	History.forward(); // Go back
};

// Add to links
document.id("backLink").addEvent("click",back);
document.id("forwardLink").addEvent("click",forward);


The next step is adding a change event to History itself to run our loadPage function when the page URL changes:

下一步是将change事件添加到“历史记录”本身,以便在页面URL更改时运行我们的loadPage函数:


// When the history changes, update the content 
History.addEvent('change',loadPage);


If the client doesn't support the history.pushState method, the History plugin evaluates the hash and loads the page as necessary:

如果客户端不支持history.pushState方法,则History插件将评估哈希值并根据需要加载页面:


// Handle the initial load of the page if the browser does not support pushState, check if the hash is set
if(!History.hasPushState()) {
	// Check if there is a hash
	var hash = document.location.hash.substr(1);
	if (!hash) return;

	// If the hash equals the current page, don't do anything
	var path = document.location.pathname.split('/');
	path = path[path.length - 1];
	if (hash == path) return;

	// Load the page specified in the hash
	loadPage(hash);
}




Lastly, running the onPageUpdate upon domready load doesn't hurt since events are only added once within onPageUpdate:

最后,运行onPageUpdatedomready负载不受到伤害,因为事件仅在添加一次onPageUpdate


// Update the page
onPageUpdate();


Now the page is ready to support History-based, AJAX-driven content swapping.  Thanks to the onPageUpdate function, links are added to events as they come in so that even AJAX-retrieved content can be managed with History.

现在,该页面已准备好支持基于历史记录的AJAX驱动的内容交换。 onPageUpdate函数,可以在事件进入时将链接添加到事件中,以便甚至可以使用“历史记录”管理AJAX检索的内容。

哈希/历史管理网站的提示和策略 (Tips and Strategies for Hash/History-Managed Websites)

Plugins like Christoph's History masterpiece are very helpful in enriching the user experience but do require a bit of developer logic:

像Christoph's History杰作这样的插件在丰富用户体验方面非常有帮助,但是确实需要一些开发人员逻辑:

  • Use Event Delegation - Remember that with a History-style system, assigning events to elements directly may not be the best solution because those elements may be gone with the next link click. Using event delegation instead of traditional event assignments may save you a lot of trouble. Read my MooTools Element.Delegation post if you aren't familiar with event delegation.

    使用事件委托 -请记住,在历史记录样式的系统中,直接将事件分配给元素可能不是最佳的解决方案,因为单击下一个链接后这些元素可能会消失。 使用事件委托而不是传统的事件分配可以为您节省很多麻烦。 如果您不熟悉事件委托,请阅读我的MooTools Element.Delegation帖子。

  • Don't Assume JavaScript Support - Keep in mind that the client may not support JavaScript.  Search engines have added JavaScript support but it's important to use URLs that will work with both on a History-managed site and a JavaScript-less website.

    不接受JavaScript支持 -请记住,客户端可能不支持JavaScript。 搜索引擎增加了对JavaScript的支持,但是重要的是要使用在历史记录管理的网站和无JavaScript的网站上都可以使用的URL。

  • Use AJAX Detection - MooTools provides an AJAX-specific header within the Request class called HTTP_X_REQUESTED_WITH.  Click here to learn how to use it to detect AJAX requests.  You will want to be able to detect AJAX so that those requests simply return the content and not the header and footer (etc.) with it. You could write a client-side script/regex to parse out the content but that's largely inefficient. My demo uses PHP to store the page content in variables as follows:

    使用AJAX检测 HTTP_X_REQUESTED_WITH在Request类中提供了特定于AJAX的标头,称为HTTP_X_REQUESTED_WITH单击此处了解如何使用它来检测AJAX请求。 您将希望能够检测到AJAX,以使那些请求仅返回内容,而不返回其标题和页脚(等)。 您可以编写一个客户端脚本/正则表达式来解析内容,但这效率很低。 我的演示使用PHP将页面内容存储在变量中,如下所示:

    Use AJAX Detection - MooTools provides an AJAX-specific header within the Request class called HTTP_X_REQUESTED_WITH.  Click here to learn how to use it to detect AJAX requests.  You will want to be able to detect AJAX so that those requests simply return the content and not the header and footer (etc.) with it. You could write a client-side script/regex to parse out the content but that's largely inefficient. My demo uses PHP to store the page content in variables as follows:

    使用AJAX检测 HTTP_X_REQUESTED_WITH在Request类中提供了特定于AJAX的标头,称为HTTP_X_REQUESTED_WITH单击此处了解如何使用它来检测AJAX请求。 您将希望能够检测到AJAX,以使那些请求仅返回内容,而不返回其标题和页脚(等)。 您可以编写一个客户端脚本/正则表达式来解析内容,但这效率很低。 我的演示使用PHP将页面内容存储在变量中,如下所示:

    
    // Load pages based on querystring
    $qstring = $_SERVER['QUERY_STRING'];
    if($qstring == 'home' || $qstring == '') {
    	$content.= '<h1>Welcome Home!</h1>';
    	$content.= '<p>History Management via popstate or hashchange. Replaces the URL of the page without a reload and falls back to Hashchange on older browsers.</p><p>This demo page aims to teach you how you can use Christoph Pojer\'s outstanding History widget to load only the content you need, dynamically and reliably.</p>';
    }
    elseif($qstring == 'about-david') {
    	$content.= '<h1>About David Walsh</h1>';
    	$content.= '<p>My name is David Walsh. I\'m a 27 year old Web Developer from Madison, Wisconsin. In the web world, I am:</p>
    	<ul>
    	<li>Founder and Lead Developer for Wynq Web Labs.</li>
    	<li>Software Engineer for SitePen.</li>
    	<li>Core Developer for the MooTools JavaScript framework.</li>
    	<li>Co-Founder of Script & Style, a website aimed at making web developers and designers better.</li>
    	</ul>
    	<p>I don\'t design the websites - I make them work.</p>
    	<p>I am also an admirer of the great <a href="?about-christoph">Christoph Pojer!</a>.</p>';
    }
    // and more....
    // Page not found
    else {
    	$content.= '<h1>Page Not Found</h1>';
    	$content.= '<p>The page you were attempting to find could not be found.</p>';
    }
    
    // If request was via AJAX, push it out.
    if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    	echo $content;
    	exit();
    }
    
    
    Obviously your content management system would be pulling content from a database or other static files, but you get the point -- load content before any page output, sniff for AJAX, and push content out accordingly.  If it's not an AJAX request, push that content into the content area's HTML via traditional methods.
    

These tips should set you up well to use a History-based system.  Remember that JavaScript is meant to enhance -- keep in mind that your user (or search engine bot) may not support JavaScript, so be sure to test your website thoroughly!

这些技巧应该可以使您很好地使用基于历史记录的系统。 请记住,JavaScript是为了增强功能-请记住,您的用户(或搜索引擎机器人)可能不支持JavaScript,因此请务必彻底测试您的网站!

Give the example hell.  Click from page to page, use the back button, refresh the page, etc.  History is rock solid!

举个例子。 从页面单击到页面,使用后退按钮,刷新页面,等等。历史坚如磐石!

Thanks to Christoph Pojer for his outstanding MooTools History plugin.  Many History-style plugins have existed but the browsers haven't been as feature-rich as they are now.  If you have any suggestions, tips, or experiences to share about creating hash-based websites, please share them.

感谢Christoph Pojer出色的MooTools History插件。 已经存在许多历史风格的插件,但是浏览器并没有像现在这样具有丰富的功能。 如果您有任何关于创建基于哈希的网站的建议,技巧或经验,请分享。

翻译自: https://davidwalsh.name/mootools-history

mootools

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值