也许我是偏执狂。我总是希望我的代码尽可能的苗条。我总是把我的网站目标定在1.5MB以下(所有图片都被压缩并根据需要调整大小。我在一个月前开始使用Polymer,我想我可以从Bootstrap中删除150kbs,从jQuery中删除90kb,并拥有一个相对轻量级的站点。
我刚刚修改了elements.html文件,我很震惊。beast是947KB,没有图像,只有简单的HTML和JS。我有大约40个自定义元素+几个元素目录(我甚至还没有接近创建新元素)。(GZip是947KB中的307.40kb)(使用ASP.NET MVC5和.NET 4.6)。
使用常规的3G连接,在Chrome 52中加载大约需要5.15秒(这很糟糕)。Polymer Shop演示程序加载速度非常快(在常规3G中,冷缓存时间小于3秒)
首先,这可以接受吗?我试着在3秒之前击球(或者尽可能接近)。
另外,有许多JavaScript文件正在被加载,这是硫化的一部分,我不需要。
我看过这个要点:Vulcanize and Polymer auto Lazy Loading但我不知道该怎么办。
以下是my elements.html文件的导入:
<link rel="import" href="../bower_components/app-route/app-route.html">
<link rel="import" href="../bower_components/app-route/app-location.html">
<link rel="import" href="../bower_components/app-layout/app-drawer-layout/app-drawer-layout.html">
<link rel="import" href="../bower_components/app-layout/app-drawer/app-drawer.html">
<link rel="import" href="./pgarena-drawer/pgarena-drawer.html">
<link rel="import" href="./pgarena-navbar/pgarena-navbar.html">
<link rel="import" href="./pgarena-auth/pgarena-oauth/pgarena-oauth.html">
<link rel="import" href="./routes/pgarena-app.html">
然后我所有的定制元素(pgarena)都内置了更多的聚合物成分。
我尝试了几种组合(仅限于我的元素)和(仅限于所示的聚合物元素),结果各不相同(如预期)
我不知道该怎么办。。。在诉诸于一个老套的东西之前。。。有什么建议吗?
最佳答案
好吧,大家,忍受我吧。这将是一个很长的答案。它会变得有点毛茸茸的。首先,这是聚合物1.x溶液。我不知道2.0版有什么变化
TL;博士:
我们获取.HTML的url并使用JavaScript创建link
属性(HTML import)来加载元素。我们使用Polymer.isInstance(element)
检查聚合物,看看对象是否已设置。
代码如下:
为此,我使用了iron-pages
和自定义JavaScript。
我们有我们的应用程序,如下所示:
注意*:下面的代码我把它放在同一个文件中,你可以随心所欲地把它分开。
<!-- Main Entry point for the application. This will work as the main "Controller"-->
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/app-route/app-location.html">
<link rel="import" href="../../bower_components/app-route/app-route.html">
<link rel="import" href="../../bower_components/iron-pages/iron-pages.html">
<dom-module id="pgarena-app">
<template>
<pgarena-action-config></pgarena-action-config>
<app-route route="{{route}}"
pattern="/:page"
data="{{data}}"
tail="{{tail}}">
</app-route>
<iron-pages selected="[[data.page]]" attr-for-selected="title" fallback-selection="404">
<pgarena-home-app title="" route="[[tail]]"></pgarena-home-app>
<pgarena-tournament-app title="tournaments" route="[[tail]]"></pgarena-tournament-app>
<!--<pgarena-clash-app title="clash" route="[[tail]]"></pgarena-clash-app>-->
<pgarena-account-app title="account" route="[[tail]]"><content></content></pgarena-account-app>
<pgarena-teams-app title="teams" route="[[tail]]"></pgarena-teams-app>
<div title="404">
<h1>{{data.page}} could not be found!</h1>
</div>
</iron-pages>
</template>
<script>
(function () {
'use strict';
Polymer({
is: 'pgarena-app',
ready: function () {
/* console.log("Route is ");
console.log(this.data.page);
console.log(this.tail);*/
document.addEventListener('iron-select',
function (event) {
/*
console.log("---------------------");
console.log(event);
console.log("---------------------");*/
var element = getSelectedElement(event);
var tagName = element.tagName.toLowerCase();
LazyLoad(Polymer, element, tagName, event.target);
});
}
});
})();
</script>
我们先来看看:
我的应用程序名为:“pgarena应用程序”
我不知道这个问题是否已经修复,但是app route元素存在双向数据绑定问题。也就是说,对于铁页,我必须使用双括号
[[]]
进行单向数据绑定。App route将信息从url传递到iron页面,以便可以切换不同的元素。
这不是强制性的,我不知道这样做是否正确。我将应用程序分为“视图”,视图本身就是元素。它们加载“视图”所需的所有元素。注意:这对延迟加载没有任何影响。
注意,这些元素不包含在URL中,因为我们将延迟加载它们。
让我们转到这个元素的JavaScript部分:
<script>
(function () {
'use strict';
Polymer({
is: 'pgarena-app',
ready: function () {
document.addEventListener('iron-select',
function (event) {
var element = getSelectedElement(event);
var tagName = element.tagName.toLowerCase();
LazyLoad(Polymer, element, tagName, event.target);
});
}
});
})();
</script>
这里的代码很简单。我们定义我们的元素,并聆听铁选择事件。这标志着我们铁页已经被选中。如果元素不在那里,我们就延迟加载它。其背后的魔力在于下面的自定义JavaScript。
<script>
/**
* Defines all the routes of the imports in here
*
* This is how it goes: The Key name is the tag name of the element.
* The value is the relative URL from the elements folder.
*
* You then get the element's tag name and look for it.
*
* DO NOT PUT TRAILING SLASH BEFORE THE URL! Thanks :)
**/
var PGArena = PGArena || {};
PGArena.LazyLoad =
{
"pgarena-home-app": "routes/home/pgarena-home-app.html",
"pgarena-tournament-app": "routes/tournament/pgarena-tournament-app.html",
"pgarena-account-app": "routes/account/pgarena-account-app.html",
"pgarena-clash-app": "routes/clash/pgarena-clash-app.html",
"pgarena-teams-app": "routes/teams/pgarena-teams-app.html",
"pgarena-tournament-index-view": "views/tournament/pgarena-tournament-index-view/pgarena-tournament-index-view.html",
"pgarena-tournament-list-view": "views/tournament/pgarena-tournament-list-view/pgarena-tournament-list-view.html",
"pgarena-account-index-view": "views/account/pgarena-account-index-view/pgarena-account-index-view.html",
"pgarena-account-login-view": "views/account/pgarena-account-login-view/pgarena-account-login-view.html",
"pgarena-account-register-view": "views/account/pgarena-account-register-view/pgarena-account-register-view.html",
"pgarena-account-confirm-email-view": "views/account/pgarena-account-confirm-email-view/pgarena-account-confirm-email-view.html",
"pgarena-account-oauth-view": "views/account/pgarena-account-oauth-view/pgarena-account-oauth-view.html",
"pgarena-clash-index-view": "views/clash/pgarena-clash-index-view/pgarena-clash-index-view.html",
"pgarena-clash-brawl-view": "views/clash/pgarena-clash-brawl-view/pgarena-clash-brawl-view.html",
"pgarena-teams-index-view": "views/team/pgarena-teams-index-view/pgarena-teams-index-view.html",
"pgarena-teams-create-view": "views/team/pgarena-teams-create-view/pgarena-teams-create-view.html"
};
/**
* This variable keeps track of all the vulcanized elements.
*
**/
PGArena.Vulcanized = {
}
/**
* Global Placeholder for checking which is the selected item of the iron-selectors that
are ready for lazy loading.
**/
PGArena.IronSelected = {
}
/**
* LazyLoad
*
* Lazy Loads the elements as needed. This function is triggered by iron-select
* event. If the element is already registered, then it is not loaded again.
*
* Polymer => Dependency Injection of the Polymer object. (Polymer itself)
* element => The element (DOM-wise: a.k.a tags with everything)
* elementName => The element's name.
* selectorTrigger => The element who triggered the select.
**/
function LazyLoad(Polymer, element, elementName, selectorTrigger) {
if (Polymer.isInstance(element)) {
// console.log(elementName + " is already registered ;)");
return;
} else {
//console.log(elementName+" isn't registered. On its way for Lazy Loading!");
}
//console.log("Lazy Load Started");
var hasProp = PGArena.LazyLoad.hasOwnProperty(elementName);
if (!hasProp) {
console.log("Property " + elementName + " not found for Lazy Loading");
return;
}
var href = PGArena.LazyLoad[elementName];
LoadImportAsync(href, elementName, selectorTrigger);
}
function Spinner(elementName, active) {
var paperId = 'js-' + elementName;
var queryName = active ? elementName : paperId;
var createElem = active ? 'paper-spinner-lite' : elementName;
var elem = document.querySelector(queryName);
var spinner = document.createElement(createElem);
spinner.setAttribute('active', '');
if (elem === null || elem === undefined)
return;
console.log("Element Name is");
console.log(queryName);
console.log("Element is");
console.log(elem);
console.log("Spinner is:");
console.log(spinner);
if (active) {
spinner.setAttribute('id', 'js-' + elementName);
console.log("replacing time");
elem.parentNode.replaceChild(document.createTextNode("Caca"), elem);
//elem.parentNode.replaceChild(spinner, elem);
}
else {
console.log("Replaced");
//elem.parentNode.replaceChild(elem, spinner);
}
}
function ForcedLoad() {
}
/**
* Loads the required import and appends it to the document. It really doesn't
* matter where it is appended.
*
**/
function LoadImportAsync(href, elementName) {
var link = document.createElement('link');
link.rel = 'import';
link.href = getBaseUrl() + "/NodeJS/Polymer/app/elements/" + href;
link.setAttribute('async', ''); // make it async!
link.onload = function () { Spinner(elementName, false); }
link.onerror = function (e) { console.log("There was an error loading " + elementName + ". Please Check the URL") };
document.head.appendChild(link);
}
function getBaseUrl() {
var pathArray = location.href.split('/');
var protocol = pathArray[0];
var host = pathArray[2];
return protocol + '//' + host;
}
/**
* On non-blink browsers (a.k.a Firefox , Edge, Internet Explorer)
* The event.srcElement is undefined. We need to search for it ourselves.
*
* The way we do that is that we get the current targetted element which is the iron form.
* Retrieve its selection mechanism and the supposed element's index.
*
* We proceed by query Selecting the element in the DOM all the way until we nab it.
* Then we are faced with the next challenge. We don't know if the element is using an
* index-based approach (0, 1, 2...) or an attribute approach(title="home", title="tournament",etc.)
*
* So we proceed to fetch its selection mechanism by grabbing the attrForSelected. If null, it means that
* it is using the index-based approach. We continue and get the children position at the element.
*
* Note that selectedAttr variable will return me either the index or the selected attribute's value.
* So it's going to be 0, 1, 2 if using the index based approach.
*
**/
function getSelectedElement(event) {
if (event.srcElement !== undefined)
return event.srcElement.selectedItem;
var element = event.target;
//Get the current selected attribute:
var selectedAttr = element.selected;
//Gets the attribute that is being used for selection:
var attrForSelected = element.attrForSelected;
//This means that it is not using index based
if (attrForSelected !== null) {
return element.querySelector('[' + attrForSelected + '="' + selectedAttr + '"]');
}
//Continues using index based:
var childelem = element.children[parseInt(selectedAttr)];
return childelem;
}
</script>
我们做的第一件事是定义与我拥有的文档相关的url。为此,我定义了一个json,它的键名是
LazyLoad
的title
属性,值是这个文档(pgarena应用程序)的相对URL。我的意思是,如果我想加载
iron-pages
,而我的pgarena-tournament-app
(应用程序的主要入口点)在pgarena-app
中,而我的pgarena锦标赛应用程序在www/polymer/pgarena-app.html
中,因为这是相对的,我的JSON将是:var PGArena=PGArena | |{};
PGArena.懒人=
{
“tournament”:“routes/tournament/pgarena tournament app.html”,
};
注意PGArena.LazyLoad可以是任何东西,这是我用PGArena名称空间定义的全局变量。
然后,我们看到代码LazyLoad被称为:
function LazyLoad(Polymer, element, elementName, selectorTrigger) {
if (Polymer.isInstance(element)) {
// console.log(elementName + " is already registered ;)");
return;
} else {
//console.log(elementName+" isn't registered. On its way for Lazy Loading!");
}
//console.log("Lazy Load Started");
var hasProp = PGArena.LazyLoad.hasOwnProperty(elementName);
if (!hasProp) {
console.log("Property " + elementName + " not found for Lazy Loading");
return;
}
var href = PGArena.LazyLoad[elementName];
LoadImportAsync(href, elementName, selectorTrigger);
}
我在这里要做的是检查我要延迟加载的元素是否在我定义的JSON(PGarena.lazy load)中被引用。如果它不在那里,那么我要做的就是记录那个消息。如果它在那里,而且还没有加载,那么我通过创建HTML导入并将其附加到头部来异步加载它:
/**
* Loads the required import and appends it to the document. It really doesn't
* matter where it is appended.
*
**/
function LoadImportAsync(href, elementName) {
var link = document.createElement('link');
link.rel = 'import';
link.href = getBaseUrl() + "/NodeJS/Polymer/app/elements/" + href;
link.setAttribute('async', ''); // make it async!
link.onload = function () { Spinner(elementName, false); }
link.onerror = function (e) { console.log("There was an error loading " + elementName + ". Please Check the URL") };
document.head.appendChild(link);
}
请注意(我不知道他们是否已经解决了这个问题)。对于Firefox、Edge和Safari(我相信)的HTML导入有一个polyfill。polyfill使用XHR(AJAX)加载导入!!! 我之所以提到这一点,是因为一开始我试图拦截HTML导入,但在Google Chrome中却没有成功。
如果你还需要什么,请告诉我。如你所见,我试着用旋转器,但没有成功。希望这有帮助!