Skip to content

Instantly share code, notes, and snippets.

@willbroderick
Created March 17, 2021 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willbroderick/39961eee1c8fd8d2a9c56404fefa8b74 to your computer and use it in GitHub Desktop.
Save willbroderick/39961eee1c8fd8d2a9c56404fefa8b74 to your computer and use it in GitHub Desktop.
Script for loading JS & CSS files once (into a Shopify theme, but easy to make generic)
/*
// normal usage
theme.loadScriptOnce('https://maps.googleapis.com/maps/api/js?key=' + key, function() {
_.createMap($container);
});
// using 'before run' parameter to fix load when a site unexpectedly has RequireJS on it (by temporarily removing window.define)
if(window.define) {
theme.loadScriptOnce('https://player.vimeo.com/api/player.js', function(){
_.vimeoVars.apiReady = true;
_._loadVimeoVideos();
window.define = window.tempDefine;
}, function(){
window.tempDefine = window.define;
window.define = null;
});
} else {
theme.loadScriptOnce('https://player.vimeo.com/api/player.js', function(){
_.vimeoVars.apiReady = true;
_._loadVimeoVideos();
});
}
*/
theme.scriptsLoaded = {};
theme.loadScriptOnce = function(src, callback, beforeRun, sync) {
if(typeof theme.scriptsLoaded[src] === 'undefined') {
theme.scriptsLoaded[src] = [];
var tag = document.createElement('script');
tag.src = src;
if(sync || beforeRun) {
tag.async = false;
}
if(beforeRun) {
beforeRun();
}
if(typeof callback === 'function') {
theme.scriptsLoaded[src].push(callback);
if (tag.readyState) { // IE, incl. IE9
tag.onreadystatechange = (function() {
if (tag.readyState == "loaded" || tag.readyState == "complete") {
tag.onreadystatechange = null;
for(var i = 0; i < theme.scriptsLoaded[this].length; i++) {
theme.scriptsLoaded[this][i]();
}
theme.scriptsLoaded[this] = true;
}
}).bind(src);
} else {
tag.onload = (function() { // Other browsers
for(var i = 0; i < theme.scriptsLoaded[this].length; i++) {
theme.scriptsLoaded[this][i]();
}
theme.scriptsLoaded[this] = true;
}).bind(src);
}
}
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
return true;
} else if(typeof theme.scriptsLoaded[src] === 'object' && typeof callback === 'function') {
theme.scriptsLoaded[src].push(callback);
} else {
if(typeof callback === 'function') {
callback();
}
return false;
}
};
theme.loadStyleOnce = function(src) {
var srcWithoutProtocol = src.replace(/^https?:/, '');
if(!document.querySelector('link[href="' + encodeURI(srcWithoutProtocol) + '"]')) {
var tag = document.createElement('link');
tag.href = srcWithoutProtocol;
tag.rel = 'stylesheet';
tag.type = 'text/css';
var firstTag = document.getElementsByTagName('link')[0];
firstTag.parentNode.insertBefore(tag, firstTag);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment