444 lines
17 KiB
Plaintext
444 lines
17 KiB
Plaintext
{% doc %}
|
|
Loads delayed scripts after the first pointer, key, or wheel interaction.
|
|
A script keeps running immediately when it has the nolazy attribute.
|
|
|
|
@example
|
|
{% render 'rocket-delay' %}
|
|
{% enddoc %}
|
|
|
|
{% unless request.design_mode %}
|
|
<script nolazy>
|
|
(() => {
|
|
const exemptScript = (script) => {
|
|
if (!script || script.tagName !== 'SCRIPT') return true;
|
|
if (script.hasAttribute('nolazy') || script.hasAttribute('data-nolazy')) return true;
|
|
const type = script.getAttribute('type') || '';
|
|
return type === 'application/json' || type === 'application/ld+json' || type === 'rocketlazyloadscript';
|
|
};
|
|
|
|
const holdScript = (script) => {
|
|
if (exemptScript(script)) return;
|
|
const src = script.getAttribute('src');
|
|
if (src) {
|
|
script.setAttribute('data-rocket-src', src);
|
|
script.removeAttribute('src');
|
|
}
|
|
// Keep ES modules as modules when they are released later (prevents
|
|
// "Cannot use import statement outside a module" on runtime-injected scripts).
|
|
if ((script.getAttribute('type') || '').toLowerCase() === 'module') script.setAttribute('data-rocket-type', 'module');
|
|
script.setAttribute('type', 'rocketlazyloadscript');
|
|
};
|
|
|
|
const holdTree = (node) => {
|
|
if (!node || node.nodeType !== 1) return;
|
|
holdScript(node);
|
|
if (node.querySelectorAll) node.querySelectorAll('script').forEach(holdScript);
|
|
};
|
|
|
|
new MutationObserver((mutations) => {
|
|
mutations.forEach((mutation) => {
|
|
mutation.addedNodes.forEach(holdTree);
|
|
});
|
|
}).observe(document.documentElement, { childList: true, subtree: true });
|
|
|
|
class RocketLazyLoadScripts {
|
|
constructor() {
|
|
this.triggerEvents = ['keydown', 'mousedown', 'mousemove', 'touchmove', 'touchstart', 'touchend', 'wheel'];
|
|
this.userEventHandler = this._triggerListener.bind(this);
|
|
this.touchStartHandler = this._onTouchStart.bind(this);
|
|
this.touchMoveHandler = this._onTouchMove.bind(this);
|
|
this.touchEndHandler = this._onTouchEnd.bind(this);
|
|
this.clickHandler = this._onClick.bind(this);
|
|
this.interceptedClicks = [];
|
|
this.delayedScripts = { normal: [], async: [], defer: [] };
|
|
this.trash = [];
|
|
this.allJQueries = [];
|
|
window.addEventListener('pageshow', (event) => {
|
|
this.persisted = event.persisted;
|
|
});
|
|
window.addEventListener('DOMContentLoaded', () => {
|
|
this._preconnect3rdParties();
|
|
});
|
|
}
|
|
|
|
_addUserInteractionListener(instance) {
|
|
if (document.hidden) {
|
|
instance._triggerListener();
|
|
return;
|
|
}
|
|
this.triggerEvents.forEach((eventName) => window.addEventListener(eventName, instance.userEventHandler, { passive: true }));
|
|
window.addEventListener('touchstart', instance.touchStartHandler, { passive: true });
|
|
window.addEventListener('mousedown', instance.touchStartHandler);
|
|
document.addEventListener('visibilitychange', instance.userEventHandler);
|
|
}
|
|
|
|
_removeUserInteractionListener() {
|
|
this.triggerEvents.forEach((eventName) => window.removeEventListener(eventName, this.userEventHandler, { passive: true }));
|
|
document.removeEventListener('visibilitychange', this.userEventHandler);
|
|
}
|
|
|
|
_onTouchStart(event) {
|
|
if (event.target.tagName === 'HTML') return;
|
|
window.addEventListener('touchend', this.touchEndHandler);
|
|
window.addEventListener('mouseup', this.touchEndHandler);
|
|
window.addEventListener('touchmove', this.touchMoveHandler, { passive: true });
|
|
window.addEventListener('mousemove', this.touchMoveHandler);
|
|
event.target.addEventListener('click', this.clickHandler);
|
|
this._renameDOMAttribute(event.target, 'onclick', 'rocket-onclick');
|
|
this._pendingClickStarted();
|
|
}
|
|
|
|
_onTouchMove(event) {
|
|
window.removeEventListener('touchend', this.touchEndHandler);
|
|
window.removeEventListener('mouseup', this.touchEndHandler);
|
|
window.removeEventListener('touchmove', this.touchMoveHandler, { passive: true });
|
|
window.removeEventListener('mousemove', this.touchMoveHandler);
|
|
event.target.removeEventListener('click', this.clickHandler);
|
|
this._renameDOMAttribute(event.target, 'rocket-onclick', 'onclick');
|
|
this._pendingClickFinished();
|
|
}
|
|
|
|
_onTouchEnd() {
|
|
window.removeEventListener('touchend', this.touchEndHandler);
|
|
window.removeEventListener('mouseup', this.touchEndHandler);
|
|
window.removeEventListener('touchmove', this.touchMoveHandler, { passive: true });
|
|
window.removeEventListener('mousemove', this.touchMoveHandler);
|
|
}
|
|
|
|
_onClick(event) {
|
|
event.target.removeEventListener('click', this.clickHandler);
|
|
this._renameDOMAttribute(event.target, 'rocket-onclick', 'onclick');
|
|
this.interceptedClicks.push(event);
|
|
event.preventDefault();
|
|
event.stopPropagation();
|
|
event.stopImmediatePropagation();
|
|
this._pendingClickFinished();
|
|
}
|
|
|
|
_replayClicks() {
|
|
window.removeEventListener('touchstart', this.touchStartHandler, { passive: true });
|
|
window.removeEventListener('mousedown', this.touchStartHandler);
|
|
this.interceptedClicks.forEach((event) => {
|
|
event.target.dispatchEvent(new MouseEvent('click', { view: event.view, bubbles: true, cancelable: true }));
|
|
});
|
|
}
|
|
|
|
_waitForPendingClicks() {
|
|
return new Promise((resolve) => {
|
|
if (this._isClickPending) this._pendingClickFinished = resolve;
|
|
else resolve();
|
|
});
|
|
}
|
|
|
|
_pendingClickStarted() {
|
|
this._isClickPending = true;
|
|
}
|
|
|
|
_pendingClickFinished() {
|
|
this._isClickPending = false;
|
|
}
|
|
|
|
_renameDOMAttribute(node, from, to) {
|
|
if (node.hasAttribute && node.hasAttribute(from)) {
|
|
node.setAttribute(to, node.getAttribute(from));
|
|
node.removeAttribute(from);
|
|
}
|
|
}
|
|
|
|
_triggerListener() {
|
|
this._removeUserInteractionListener();
|
|
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', this._loadEverythingNow.bind(this));
|
|
else this._loadEverythingNow();
|
|
}
|
|
|
|
_preconnect3rdParties() {
|
|
const origins = [];
|
|
document.querySelectorAll('script[type="rocketlazyloadscript"][data-rocket-src], script[type="rocketlazyloadscript"][src]').forEach((script) => {
|
|
let src = script.getAttribute('data-rocket-src') || script.getAttribute('src');
|
|
if (!src || src.indexOf('data:') === 0) return;
|
|
if (src.indexOf('//') === 0) src = location.protocol + src;
|
|
try {
|
|
const origin = new URL(src, location.href).origin;
|
|
if (origin !== location.origin) {
|
|
origins.push({ src: origin, crossOrigin: script.crossOrigin || (script.getAttribute('data-rocket-type') === 'module') });
|
|
}
|
|
} catch (error) {
|
|
origins.push(error);
|
|
}
|
|
});
|
|
const unique = [...new Map(origins.filter((item) => item && item.src).map((item) => [item.src, item])).values()];
|
|
this._batchInjectResourceHints(unique, 'preconnect');
|
|
}
|
|
|
|
async _loadEverythingNow() {
|
|
this.lastBreath = Date.now();
|
|
this._delayEventListeners();
|
|
this._delayJQueryReady();
|
|
this._handleDocumentWrite();
|
|
this._registerAllDelayedScripts();
|
|
this._preloadAllScripts();
|
|
await this._loadScriptsFromList(this.delayedScripts.normal);
|
|
await this._loadScriptsFromList(this.delayedScripts.defer);
|
|
await this._loadScriptsFromList(this.delayedScripts.async);
|
|
try {
|
|
await this._triggerDOMContentLoaded();
|
|
await this._pendingWebpackRequests();
|
|
await this._triggerWindowLoad();
|
|
} catch (error) {
|
|
console.error(error);
|
|
}
|
|
window.dispatchEvent(new Event('rocket-allScriptsLoaded'));
|
|
this._waitForPendingClicks().then(() => {
|
|
this._replayClicks();
|
|
});
|
|
this._emptyTrash();
|
|
}
|
|
|
|
_isExempt(script) {
|
|
if (script.hasAttribute('nolazy') || script.hasAttribute('data-nolazy')) return true;
|
|
const type = script.getAttribute('type') || '';
|
|
return type === 'application/json' || type === 'application/ld+json';
|
|
}
|
|
|
|
_registerAllDelayedScripts() {
|
|
document.querySelectorAll('script[type="rocketlazyloadscript"]').forEach((script) => {
|
|
if (this._isExempt(script) || !script.isConnected) return;
|
|
const src = script.getAttribute('data-rocket-src') || script.getAttribute('src');
|
|
const moduleScript = script.getAttribute('data-rocket-type') === 'module';
|
|
if (src) {
|
|
if (script.hasAttribute('async') && script.async !== false) this.delayedScripts.async.push(script);
|
|
else if (script.hasAttribute('defer') || moduleScript) this.delayedScripts.defer.push(script);
|
|
else this.delayedScripts.normal.push(script);
|
|
} else {
|
|
this.delayedScripts.normal.push(script);
|
|
}
|
|
});
|
|
}
|
|
|
|
async _transformScript(script) {
|
|
await this._littleBreath();
|
|
if (script.noModule && 'noModule' in HTMLScriptElement.prototype) {
|
|
script.setAttribute('data-rocket-status', 'skipped');
|
|
return;
|
|
}
|
|
await new Promise((resolve) => {
|
|
const next = document.createElement('script');
|
|
[...script.attributes].forEach((attribute) => {
|
|
let name = attribute.nodeName;
|
|
if (name === 'type') return;
|
|
if (name === 'data-rocket-type') name = 'type';
|
|
if (name === 'data-rocket-src') name = 'src';
|
|
next.setAttribute(name, attribute.nodeValue);
|
|
});
|
|
const src = script.getAttribute('data-rocket-src') || script.getAttribute('src');
|
|
if (src) next.src = src;
|
|
else if (script.text) next.text = script.text;
|
|
if (next.src) {
|
|
next.addEventListener('load', () => resolve());
|
|
next.addEventListener('error', () => resolve());
|
|
}
|
|
try {
|
|
script.parentNode.replaceChild(next, script);
|
|
} catch (error) {
|
|
resolve();
|
|
return;
|
|
}
|
|
if (!next.src) resolve();
|
|
});
|
|
}
|
|
|
|
async _loadScriptsFromList(list) {
|
|
const script = list.shift();
|
|
if (!script || !script.isConnected) return;
|
|
await this._transformScript(script);
|
|
await this._loadScriptsFromList(list);
|
|
}
|
|
|
|
_preloadAllScripts() {
|
|
this._batchInjectResourceHints([...this.delayedScripts.normal, ...this.delayedScripts.defer, ...this.delayedScripts.async], 'preload');
|
|
}
|
|
|
|
_batchInjectResourceHints(items, rel) {
|
|
const fragment = document.createDocumentFragment();
|
|
items.forEach((item) => {
|
|
const src = (item.getAttribute && (item.getAttribute('data-rocket-src') || item.getAttribute('src'))) || item.src;
|
|
if (!src) return;
|
|
const link = document.createElement('link');
|
|
link.href = src;
|
|
link.rel = rel;
|
|
if (rel !== 'preconnect') link.as = 'script';
|
|
if (item.crossOrigin) link.crossOrigin = item.crossOrigin;
|
|
if (item.getAttribute && item.getAttribute('data-rocket-type') === 'module') link.crossOrigin = 'anonymous';
|
|
if (item.integrity) link.integrity = item.integrity;
|
|
fragment.appendChild(link);
|
|
this.trash.push(link);
|
|
});
|
|
document.head.appendChild(fragment);
|
|
}
|
|
|
|
_delayEventListeners() {
|
|
const registry = {};
|
|
const wrapTarget = (target) => {
|
|
if (registry[target]) return;
|
|
registry[target] = {
|
|
originalFunctions: { add: target.addEventListener, remove: target.removeEventListener },
|
|
eventsToRewrite: [],
|
|
};
|
|
target.addEventListener = function addEventListener(...args) {
|
|
args[0] = rename(args[0]);
|
|
registry[target].originalFunctions.add.apply(target, args);
|
|
};
|
|
target.removeEventListener = function removeEventListener(...args) {
|
|
args[0] = rename(args[0]);
|
|
registry[target].originalFunctions.remove.apply(target, args);
|
|
};
|
|
function rename(eventName) {
|
|
return registry[target].eventsToRewrite.indexOf(eventName) >= 0 ? `rocket-${eventName}` : eventName;
|
|
}
|
|
};
|
|
const rewrite = (target, eventName) => {
|
|
wrapTarget(target);
|
|
registry[target].eventsToRewrite.push(eventName);
|
|
};
|
|
const delayProperty = (target, property) => {
|
|
let value = target[property];
|
|
Object.defineProperty(target, property, {
|
|
get: () => value || function noop() {},
|
|
set(next) {
|
|
target[`rocket${property}`] = value = next;
|
|
},
|
|
});
|
|
};
|
|
rewrite(document, 'DOMContentLoaded');
|
|
rewrite(window, 'DOMContentLoaded');
|
|
rewrite(window, 'load');
|
|
rewrite(window, 'pageshow');
|
|
rewrite(document, 'readystatechange');
|
|
delayProperty(document, 'onreadystatechange');
|
|
delayProperty(window, 'onload');
|
|
delayProperty(window, 'onpageshow');
|
|
}
|
|
|
|
_delayJQueryReady() {
|
|
let current;
|
|
const renameLoad = (events) => events.split(' ').map((eventName) => (eventName === 'load' || eventName.indexOf('load.') === 0 ? 'rocket-jquery-load' : eventName)).join(' ');
|
|
const patch = (jquery) => {
|
|
if (!jquery || !jquery.fn || this.allJQueries.includes(jquery)) {
|
|
current = jquery;
|
|
return;
|
|
}
|
|
jquery.fn.ready = jquery.fn.init.prototype.ready = (callback) => {
|
|
if (this.domReadyFired) callback.bind(document)(jquery);
|
|
else document.addEventListener('rocket-DOMContentLoaded', () => callback.bind(document)(jquery));
|
|
return jquery([]);
|
|
};
|
|
const originalOn = jquery.fn.on;
|
|
jquery.fn.on = jquery.fn.init.prototype.on = function on(...args) {
|
|
if (this[0] === window) {
|
|
if (typeof args[0] === 'string') args[0] = renameLoad(args[0]);
|
|
else if (args[0] && typeof args[0] === 'object') {
|
|
Object.keys(args[0]).forEach((key) => {
|
|
const handler = args[0][key];
|
|
delete args[0][key];
|
|
args[0][renameLoad(key)] = handler;
|
|
});
|
|
}
|
|
}
|
|
return originalOn.apply(this, args);
|
|
};
|
|
this.allJQueries.push(jquery);
|
|
current = jquery;
|
|
};
|
|
patch(window.jQuery);
|
|
Object.defineProperty(window, 'jQuery', {
|
|
get: () => current,
|
|
set: patch,
|
|
});
|
|
}
|
|
|
|
async _pendingWebpackRequests() {
|
|
const script = document.querySelector('script[data-webpack]');
|
|
if (!script) return;
|
|
await new Promise((resolve) => {
|
|
script.addEventListener('load', resolve);
|
|
script.addEventListener('error', resolve);
|
|
});
|
|
await this._requestAnimFrame();
|
|
await this._pendingWebpackRequests();
|
|
}
|
|
|
|
async _triggerDOMContentLoaded() {
|
|
this.domReadyFired = true;
|
|
await this._littleBreath();
|
|
document.dispatchEvent(new Event('rocket-DOMContentLoaded'));
|
|
await this._littleBreath();
|
|
window.dispatchEvent(new Event('rocket-DOMContentLoaded'));
|
|
await this._littleBreath();
|
|
document.dispatchEvent(new Event('rocket-readystatechange'));
|
|
await this._littleBreath();
|
|
if (document.rocketonreadystatechange) document.rocketonreadystatechange();
|
|
}
|
|
|
|
async _triggerWindowLoad() {
|
|
await this._littleBreath();
|
|
window.dispatchEvent(new Event('rocket-load'));
|
|
await this._littleBreath();
|
|
if (window.rocketonload) window.rocketonload();
|
|
await this._littleBreath();
|
|
this.allJQueries.forEach((jquery) => jquery(window).trigger('rocket-jquery-load'));
|
|
await this._littleBreath();
|
|
const pageShow = new Event('rocket-pageshow');
|
|
pageShow.persisted = this.persisted;
|
|
window.dispatchEvent(pageShow);
|
|
await this._littleBreath();
|
|
if (window.rocketonpageshow) window.rocketonpageshow({ persisted: this.persisted });
|
|
}
|
|
|
|
_handleDocumentWrite() {
|
|
const nextSibling = new Map();
|
|
const write = (markup) => {
|
|
const current = document.currentScript;
|
|
if (!current) return;
|
|
const range = document.createRange();
|
|
const parent = current.parentElement;
|
|
let marker = nextSibling.get(current);
|
|
if (marker === undefined) {
|
|
marker = current.nextSibling;
|
|
nextSibling.set(current, marker);
|
|
}
|
|
const fragment = document.createDocumentFragment();
|
|
range.setStart(fragment, 0);
|
|
fragment.appendChild(range.createContextualFragment(markup));
|
|
parent.insertBefore(fragment, marker);
|
|
};
|
|
document.write = write;
|
|
document.writeln = write;
|
|
}
|
|
|
|
async _littleBreath() {
|
|
if (Date.now() - this.lastBreath > 45) {
|
|
await this._requestAnimFrame();
|
|
this.lastBreath = Date.now();
|
|
}
|
|
}
|
|
|
|
async _requestAnimFrame() {
|
|
if (document.hidden) await new Promise((resolve) => setTimeout(resolve));
|
|
else await new Promise((resolve) => requestAnimationFrame(resolve));
|
|
}
|
|
|
|
_emptyTrash() {
|
|
this.trash.forEach((node) => node.remove());
|
|
}
|
|
|
|
static run() {
|
|
const instance = new RocketLazyLoadScripts();
|
|
instance._addUserInteractionListener(instance);
|
|
}
|
|
}
|
|
|
|
RocketLazyLoadScripts.run();
|
|
})();
|
|
</script>
|
|
{% endunless %}
|