This repository has been archived by the owner on Feb 13, 2019. It is now read-only.
/
lazy-template.js
68 lines (54 loc) · 1.73 KB
/
lazy-template.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import { registerElement } from 'bulbs-elements/register';
import { InViewMonitor } from 'bulbs-elements/util';
import invariant from 'invariant';
import './lazy-template.scss';
function BulbsHTMLScriptElement () {}
BulbsHTMLScriptElement.prototype = HTMLScriptElement.prototype;
class LazyTemplate extends BulbsHTMLScriptElement {
get loadOn () {
return this.getAttribute('load-on');
}
attachedCallback () {
invariant(this.hasAttribute('load-on'),
'<script is="lazy-template"> MUST specify a "load-on" attribute (either "page-load" or "in-view").');
invariant(this.getAttribute('type') === 'text/html',
'<script is="lazy-template"> MUST set the attribute type="text/html".');
if (this.loadOn === 'page-load') {
this.setupLoadOnPageLoad();
}
else if (this.loadOn === 'in-view') {
this.setUpLoadOnInView();
}
this.replaceWithContents = this.replaceWithContents.bind(this);
this.handleEnterViewport = this.handleEnterViewport.bind(this);
}
detachedCallback () {
if (this.loadOn === 'in-view') {
this.tearDownLoadOnInView();
}
}
setupLoadOnPageLoad () {
if (document.readyState === 'complete') {
this.replaceWithContents();
}
else {
window.addEventListener('load', () => this.replaceWithContents());
}
}
setUpLoadOnInView () {
InViewMonitor.add(this);
this.addEventListener('enterviewport', this.handleEnterViewport);
}
handleEnterViewport () {
InViewMonitor.remove(this);
this.replaceWithContents();
}
tearDownLoadOnInView () {
InViewMonitor.remove(this);
}
replaceWithContents () {
this.outerHTML = this.textContent;
}
}
LazyTemplate.extends = 'script';
registerElement('lazy-template', LazyTemplate);