Optionally use Intersection Observer to late-load cards (#906)

This commit is contained in:
Andrey 2018-02-21 10:00:52 +02:00 committed by Paulus Schoutsen
parent 346022c48e
commit ea57e71c8b
2 changed files with 45 additions and 9 deletions

View File

@ -20,14 +20,51 @@ class HaCardChooser extends Polymer.Element {
};
}
cardDataChanged(newData) {
if (!newData) return;
_updateCard(newData) {
window.hassUtil.dynamicContentUpdater(
this, 'HA-' + newData.cardType.toUpperCase() + '-CARD',
newData
);
}
cardDataChanged(newData) {
if (!newData) return;
// ha-entities-card is exempt from observer as it doesn't load heavy resources.
// and usually doesn't load external resources (except for entity_picture).
const eligibleToObserver =
(window.IntersectionObserver && newData.cardType !== 'entities');
if (!eligibleToObserver) {
if (this.observer) {
this.observer.unobserve(this);
this.observer = null;
}
this._updateCard(newData);
return;
}
if (!this.observer) {
this.observer = new IntersectionObserver((entries) => {
if (!entries.length) return;
if (entries[0].isIntersecting) {
this.style.height = '';
if (this._detachedChild) {
this.appendChild(this._detachedChild);
this._detachedChild = null;
}
this._updateCard(this.cardData); // Don't use 'newData' as it might have chnaged.
} else {
// Set the card to be 48px high. Otherwise if the card is kept as 0px height then all
// following cards would trigger the observer at once.
const offsetHeight = this.offsetHeight;
this.style.height = `${offsetHeight || 48}px`;
if (this.lastChild) {
this._detachedChild = this.lastChild;
this.removeChild(this.lastChild);
}
}
});
this.observer.observe(this);
}
}
}
customElements.define(HaCardChooser.is, HaCardChooser);
</script>

View File

@ -29,7 +29,8 @@
overflow-x: hidden;
}
.zone-card {
ha-card-chooser {
display: block;
margin-left: 8px;
margin-bottom: 8px;
}
@ -39,7 +40,7 @@
padding-right: 0;
}
.zone-card {
ha-card-chooser {
margin-left: 0;
}
}
@ -66,10 +67,8 @@
<template is='dom-repeat' items='[[cards.columns]]' as='column'>
<div class='column flex-1'>
<template is='dom-repeat' items='[[column]]' as='card'>
<div class='zone-card'>
<ha-card-chooser card-data='[[card]]' hass='[[hass]]'
></ha-card-chooser>
</div>
<ha-card-chooser card-data='[[card]]' hass='[[hass]]'
></ha-card-chooser>
</template>
</div>
</template>