Skip to content

Instantly share code, notes, and snippets.

@muzi131313
Created November 24, 2021 03:41
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 muzi131313/aa19253d28ee2189d53b58d8b70ad115 to your computer and use it in GitHub Desktop.
Save muzi131313/aa19253d28ee2189d53b58d8b70ad115 to your computer and use it in GitHub Desktop.
动态加script
function loadScript(url, attributesParam, optsParam) {
var attributes = attributesParam || {};
// optional
var opts = optsParam || {};
var script = document.createElement('script');
// default value
if (attributes.defer === undefined) {
attributes.defer = true;
}
if (opts.async === undefined) {
attributes.async = true;
}
// optional attribute
for (var attributeKey in attributes) {
script.setAttribute(attributeKey, attributes[attributeKey]);
}
// load url
script.src = url;
// callback
script.onload = function() {
if (opts.onload) opts.onload();
};
script.onerror = function() {
if (opts.onerror) opts.onerror();
};
// load script
var _loadScript = function() {
if (opts.appendBody) {
var body = document.getElementsByTagName('body')[0];
body.appendChild(script);
}
else {
var lastScript = document.getElementsByTagName('script')[0];
lastScript.parentNode.insertBefore(script, lastScript);
}
};
// timeout support
if (opts.timeout) {
setTimeout(function() {
_loadScript();
}, opts.timeout);
}
else {
_loadScript();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment