mootools_使用MooTools和RequireJS延迟加载内容和小部件

mootools

The idea of lazy loading content is not new;  we've been lazy loading images (check out my MooTools LazyLoad plugin) for quite a while now.  And why wouldn't you lazy load content?  There are SEO advantages, load time advantages, bandwidth savings, and more, so including a bit of extra JavaScript could help your large website immensely.  In my latest redesign, I took the time to lazy load not just images but static content and social networking widgets to make my website's initial load happen faster to make user experience and Google rank improve.  Let me show you how I used MooTools and RequireJS to lazy load content.

延迟加载内容的想法并不新鲜; 我们一直在懒惰地加载图像(请查看我的MooTools LazyLoad插件)已经有一段时间了。 而且,为什么您不懒加载内容? 它具有SEO优势,加载时间优势,带宽节省等优点,因此包含一些额外JavaScript可以极大地帮助您的大型网站。 在我最新的重新设计中,我花了一些时间来懒惰加载,不仅是图像,还有静态内容和社交网络小部件,它们使我的网站的初始加载速度更快,从而提高了用户体验和Google排名。 让我向您展示如何使用MooTools和RequireJS延迟加载内容。

So what am I lazy loading within my current design?

那么,我在当前设计中的延迟加载是什么?

  • Twitter, Facebook, and Google Plus widgets for single blog posts.

    Twitter,Facebook和Google Plus小部件,用于单个博客文章。
  • Page footer;  since the footer content is out of sight during initial page load, it doesn't need to be loaded right away.

    页脚; 由于页脚内容在初始页面加载期间不可见,因此不需要立即加载。
  • LighterJS Syntax Highlighter; if no PRE tag is on the page, there's no reason to grab the syntax highlighter.

    LighterJS语法荧光笔; 如果页面上没有PRE标签,则没有理由获取语法荧光笔。
  • Comment avatar images;  there's no point to loading these images immediately as they must be scrolled to.  If someone hits the "#comments" portion of the page, my LazyLoad plugin can handle loading the initial images.

    评论头像图片; 没有必要立即加载这些图像,因为必须将其滚动到。 如果有人点击页面的“ #comments”部分,我的LazyLoad插件可以处理加载初始图像。
  • Tweets;  tweet content is non-essential so they needn't be loaded right away.

    推文 推文内容不是必需的,因此无需立即加载。
  • MooTools StarRating;  again, only needed if it's a post page.

    MooTools StarRating; 同样,仅在帖子页面时才需要。

Of course, there needs to be a trigger for these items to load.  I've chosen three events to trigger loading of these components:  keydown, mousemove, and scroll.  Each of these events signify a human and "interested" presence.  Let me show you how I've implemented this lazy loading.

当然,需要触发这些项目才能加载。 我选择了三个事件来触发这些组件的加载:按下键盘,鼠标移动和滚动。 这些事件中的每一个都表示人类和“感兴趣的”存在。 让我向您展示如何实现这种延迟加载。

加载初始脚本 (Load Initial Scripts)

Not every script can be asynchronously loaded, so the scripts I do load synchronously are RequireJS and Google's JSAPI (for Analytics and Google Search):

并非每个脚本都可以异步加载,因此我确实同步加载的脚本是RequireJS和Google的JSAPI(用于Analytics和Google搜索):


<!-- JavaScript at the bottom for fast page loading --> 
<script src="http://ajax.cdnjs.com/ajax/libs/require.js/0.23.0/require.min.js"></script> 
<script src="https://www.google.com/jsapi?key=MY_KEY"></script> 
<script> 
	// Load MooTools, Google Search
	function loadScripts() { 
		require(["https://davidwalsh.name/wp-content/themes/klass/js/script.js"]); 
	}
	google.load("mootools", "1.3.0");
	google.load("search", "1");
	google.setOnLoadCallback(loadScripts);
</script>


Once the scripts are loaded, my theme's main JavaScript resources is required.

加载脚本后,就需要主题的主要JavaScript资源。

延迟加载代码 (Lazy Loading Code)

Since there are multiple tasks I want to run when the user "awakens," I create an onAwaken array that will hold each of the tasks.  A series of functions will be pushed to the array, each representing a sign task.  For example, the task which loads Twitter, Facebook, and Google +1 badges looks like:

由于有多个任务要在用户“唤醒”时运行,因此我创建了一个onAwaken数组来保存每个任务。 一系列函数将被推到数组中,每个函数代表一个签名任务。 例如,加载Twitter,Facebook和Google +1徽章的任务如下所示:


// Create the array of awaken functions
var onAwaken = [];

// Get the share URL from this page via the canonical link
var cannons = $$("link[rel=canonical]"), shareUrl;
if(cannons.length) {
	shareUrl = cannons[0].get("href");
}

// If the PROMO DIV exists on the page
var promoDiv = document.id("promo");
if(promoDiv && shareUrl) {
	onAwaken.push(function(){
	
		// Create a SPAN and A for the Twitter share link
		var span1 = new Element("span",{ style:"display:inline-block;float:left;" }).inject(promoDiv);
		new Element("a",{
			href: "http://twitter.com/share",
			"class": "twitter-share-button",
			"data-count": "horizontal"
		}).inject(span1);
		
		// Inject the Twitter SCRIPT tag into the SPAN
		new Element("script",{
			src: "http://platform.twitter.com/widgets.js",
			async: true
		}).inject(span1);
		
		// Create the Facebook IFRAME
		new Element("iframe",{
			src: "http://www.facebook.com/plugins/like.php?href=" + shareUrl,
			scrolling: "no",
			frameborder: 0,
			allowTransparency: true,
			style: "border:none; overflow:hidden; width:500px;"
		}).inject(new Element("span",{style:"display:inline-block;"}).inject(promoDiv));
		
		// Create the G+1 Button
		var el = document.id(document.createElement("g:plusone")).set({
			href: shareUrl,
			size: "medium"
		}).inject(new Element("span",{style:"display:inline-block;"}).inject(promoDiv));
		
		// Get the G+ SCRIPT
		require(["http://apis.google.com/js/plusone.js"],function() {
			// console.warn("G+1 is ready!");
		});
		
		// Fade in all of the lazy loaded content
		promoDiv.fade(1);
	});
}


Note that a require call is within this function, which could probably be considering lazy loading during lazy loading.  In all seriousness though, it's important to note that entire resources are lazy loaded, not just execution of available functionality.

请注意,此函数内有一个require调用,这可能是在延迟加载期间考虑了延迟加载。 严格地说,重要的是要注意整个资源都是延迟加载的,而不仅仅是执行可用功能。

Another onAwaken function includes loading of my footer and right column content:

另一个onAwaken函数包括加载我的页脚和右列内容:


// Uses Moo to load and place content
function loadAndPlace(url,where,then) {
	new Request({
		url: url,
		onSuccess: function(content) {
			document.id(where).set("html",content);
			if(then) then();
		}
	}).send();
}

// Load footer and right column upon awakening
onAwaken.push(function() { 
	loadAndPlace(themePath + "footer.html","footer"); 
});
onAwaken.push(function() { 
	loadAndPlace(themePath + "follow-trends.html","contentRightColumn", function(){ 
		$$(".contentRightColumn").fade(1); 
	}); 
});


And then I also lazy load the MooTools StarRating plugin:

然后我也懒加载MooTools StarRating插件:


// Star ratings
var ratingForm = document.id("ratingForm"),
	themePath = "/wp-content/themes/klass/";
if(ratingForm) {
	// Get the post id
	var postId = document.id("postId").get("value");
	
	// Get star ratings
	require([themePath + "js/ratings/Source/moostarrating.js"], function() {
		// Set image vars
		MooStarRatingImages = {
			defaultImageFolder: themePath + 'js/ratings/Graphics/',
			defaultImageEmpty:  'star_boxed_empty.png',
			defaultImageFull:   'star_boxed_full.png',
			defaultImageHover:  'star_boxed_hover.png'
		};
		// Create star ratings
		var voted = false;
		var rater = new MooStarRating({
			form: ratingForm,
			radios: "rating",
			half: true,
			width: 16
		}).addEvent("click",function(value) {
			if(!voted){
				// Send request
				new Request({
					url: themePath + "rating.php",
					method: "post",
					data: {
						rating: value,
						id: postId
					}
				}).send();
				// Mark as voted
				voted = true;
			}
		});
		// Fix the value...wtf?!
		// Adding 0.5 because it's always showing up short 0.5 short.  WTF.
		rater.setValue((rater.currentIndex * 0.5) + 0.5);
		// Showtime
		ratingForm.setStyle("display","block");
	});
}


There is no limit to the number of functions you can fire when the user awakens, so let's assume I have a bunch more functions ready to run.  Now it's time to place JavaScript code into place to listen for the page's awakening.  Here it goes:

用户唤醒时可以激发的功能数量没有限制,所以让我们假设我还有很多功能可以运行。 现在是时候将JavaScript代码放置到位,以侦听页面的唤醒了。 它去了:


// Set up main register handler
var runEvents = ["keydown","mousemove","scroll"];
var runAwaken = function() {
	onAwaken.each(function(evt,index) {
		evt();
	});
	// Since we've run all items, let's remove the events
	runEvents.each(function(evtType){
		window.removeEvent(evtType,runAwaken);
	});
};
// Set registers in motion
runEvents.each(function(evtType){
	window.addEvent(evtType,runAwaken);
});


First we create an array of events we want the page to awaken on.  Next we create a function which will run upon awakening;  this function will run all awaken events and then remove the event from the window so that the runAwaken function will only run once.

首先,我们创建一个事件数组,我们希望页面被唤醒。 接下来,我们创建一个将在唤醒时运行的函数; 此函数将运行所有唤醒事件,然后从窗口中删除该事件,以便runAwaken函数仅运行一次。

The sky is the limit with the content you can lazy load.  I highly recommend evaluating your website for components which don't hold search engine value, or may speed up the load of your page (especially synchronous SCRIPT tags!).  As always, have fun with your websites and do what you can to make them load faster!

天空是您可以懒加载的内容的极限。 我强烈建议您对网站进行评估,以查找不具有搜索引擎价值的组件,或者可能会加速页面加载的组件(尤其是同步的SCRIPT标签!)。 与往常一样,请与您的网站一起玩乐,并尽一切努力使它们更快地加载!

翻译自: https://davidwalsh.name/lazy-load-requirejs

mootools

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值