Skip to content

Instantly share code, notes, and snippets.

@savchukoleksii
Created February 16, 2023 20:29
Show Gist options
  • Save savchukoleksii/a868e32aa7679a5253623a44d580a010 to your computer and use it in GitHub Desktop.
Save savchukoleksii/a868e32aa7679a5253623a44d580a010 to your computer and use it in GitHub Desktop.
<script>
let temp = document.createElement("div");
temp.innerHTML = document.getElementById('shopify_header_scripts').innerHTML
.replace('</head>', '');
let elements = temp.children;
let lazyElements = [];
// Loop through each element
for (var i = 0; i < elements.length; i++) {
// Create a new element
let newElement = document.createElement(elements[i].tagName);
// Get all the attributes of the element
let attributes = elements[i].attributes;
// Insert the innerHTML of the element
if (elements[i].innerHTML) {
newElement.innerHTML = elements[i].innerHTML;
}
// Loop through each attribute
for (let j = 0; j < attributes.length; j++) {
let attribute = attributes[j];
newElement.setAttribute(attribute.name, attribute.value);
}
if(newElement.tagName === 'SCRIPT') {
lazyElements.push(newElement);
} else {
document.head.appendChild(newElement);
}
}
let lazyLoadShopifyScripts = function() {
lazyElements.forEach(function(element) {
document.head.appendChild(element);
});
}
document.body.addEventListener('touchstart', lazyLoadShopifyScripts, { once: true });
document.body.addEventListener('mouseover', lazyLoadShopifyScripts, { once: true });
</script>
<!-- This snippet tricks Shopify into injecting their end of head tags and lets me parse and re-inject it -->
<noscript id="shopify_header_scripts">
</head>
</noscript>
</head>
{% comment %}{{ content_for_header }}{% endcomment %}
{% capture header_scripts %}
{{ content_for_header }}
{% endcapture %}
{% assign header_scripts = header_scripts | replace: 's.src = urls[i]', 'if(!/^\?/.test(urls[i])) s.src = urls[i] ' %}
{% assign header_scripts = header_scripts | replace: "window.addEventListener('load', asyncLoad, false)", "document.body.addEventListener('touchstart', asyncLoad, { once: true }); document.body.addEventListener('mouseover', asyncLoad, { once: true });" %}
{{ header_scripts }}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment