tauri/cli/tauri.js/templates/mutation-observer.js
Lucas Fernandes Nogueira 78f1e03495
feat(tauri.js) inject MutationObserver to lazy load JS/CSS on no… (#355)
* feat(tauri.js) inject MutationObserver to lazy load scripts on no-server

* feat(tauri.js) add disable inliner config

* fix(tauri.js) add types

* feat(tauri.js&tauri) lazy load CSS files on mutation observer
2020-01-27 10:03:27 -03:00

46 lines
1.2 KiB
JavaScript

(function () {
function loadAsset(path, type) {
if (path) {
if (window.tauri !== void 0) {
window.tauri.loadAsset(path, type)
} else {
if (window.__TAURI_INIT_HOOKS === void 0) {
window.__TAURI_INIT_HOOKS = []
}
window.__TAURI_INIT_HOOKS.push(function () {
window.tauri.loadAsset(path, type)
})
}
}
}
var observer = new MutationObserver(mutation => {
mutation.forEach(function (mutationRecord) {
var addedNodes = mutationRecord.addedNodes
addedNodes.forEach(function (node) {
if (node.nodeType === 1) {
if (node.tagName === 'SCRIPT') {
node.onload = node.onerror = null
loadAsset(node.src)
} else if (node.tagName === 'LINK') {
if (node.type === 'text/css' || (node.href && node.href.endsWith('.css'))) {
loadAsset(node.href, 'stylesheet')
}
}
}
})
})
})
<% if (target === 'body') { %>
var target = document.documentElement
<% } else { %>
var target = document.head
<% } %>
observer.observe(target, {
childList: true,
subtree: true
})
})()