Last active
April 23, 2020 20:25
-
-
Save szepeviktor/26c1fa7bc3b376cf8d879c01758ce06c to your computer and use it in GitHub Desktop.
Mini JavaScript loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<script id="in-head"> | |
/*jslint | |
browser:true | |
*/ | |
/** | |
* Load a script in an asynchronous manner. | |
* @param {string} uri | |
* @param {callback} loadCallback | |
* @param {callback} errorCallback | |
*/ | |
function _loadScriptAsync(uri, loadCallback, errorCallback) { | |
"use strict"; | |
var element; | |
var firstScript; | |
var hash; | |
hash = uri.split("").reduce(function (a, b) { | |
a = ((a<<5) - a) + b.charCodeAt(0); | |
return a&a; | |
}, 0); | |
firstScript = document.getElementsByTagName("script")[0]; | |
element = document.createElement("script"); | |
element.src = uri; | |
element.async = true; | |
element.id = "script_" + String(hash).replace("-", "m"); | |
if (typeof loadCallback === "function") { | |
element.onload = loadCallback; | |
} | |
if (typeof errorCallback === "function") { | |
element.onerror = errorCallback; | |
} | |
firstScript.parentNode.insertBefore(element, firstScript); | |
return element.id | |
} | |
function prefixLoadContactForm(forms) { | |
_loadScriptAsync("https://code.jquery.com/jquery-3.3.1.slim.min.js", function () { | |
// Set up contact forms | |
jQuery(forms).each(function (index, form) { | |
jQuery(form).css("backgroundColor", "green"); | |
}); | |
}, function () { | |
// Report error | |
// https://docs.bugsnag.com/platforms/javascript/reporting-handled-errors/ | |
if (typeof bugsnagClient !== "object" ) { | |
return; | |
} | |
bugsnagClient.notify(new Error("Script load error")); | |
}); | |
} | |
</script> | |
<script id="in-body-footer"> | |
(function () { | |
var contactForms; | |
contactForms = document.querySelectorAll('#main'); | |
if (contactForms.length === 0) { | |
return; | |
} | |
prefixLoadContactForm(contactForms); | |
}()); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TODO Separate attrs: