Skip to content

Instantly share code, notes, and snippets.

@mgd020 mgd020/util.js
Last active Jun 2, 2018

Embed
What would you like to do?
basic javascript utils
function element(tagName) {
/*
create an element
arguments: tagName, [attributes], children...
*/
// help the minifier out a bit
var args = arguments
var doc = document
var element = doc.createElement(tagName)
if (args.length > 1) {
var i = 1
// attributes
var attributes = args[i]
if (typeof attributes === 'object' && !(attributes instanceof Node)) {
for (var name in attributes) {
var value = attributes[name]
if (typeof value === 'function') {
element[name] = value
} else {
element.setAttribute(name, value)
}
}
++i
}
// children
for (; i < args.length; ++i) {
var arg = args[i]
if (typeof arg === 'string') {
arg = doc.createTextNode(arg)
}
element.appendChild(arg)
}
}
return element
}
window.urlencode = (function() {
var encodeComponent = encodeURIComponent
return function(params) {
return Object.keys(params).map(function (key) {
return encodeComponent(key) + '=' + encodeComponent(params[key])
}).join('&').replace(/%20/g, '+')
}
})()
window.request = (function() {
/*
make a HTTP request and return a promise
rejects on non-2xx http status codes, error or timeout
arguments: url, [options]
includes usual XHR options, plus:
* headers: set request headers
* mimeType: override mime type
*/
return function(url, options) {
// url, options={}
return new Promise(function (resolve, reject) {
options = options || {}
var xhr = new XMLHttpRequest()
if (options.timeout) xhr.timeout = options.timeout
if (options.responseType) xhr.responseType = options.responseType
if (options.withCredentials) xhr.withCredentials = options.withCredentials
if (options.mimeType) xhr.overrideMimeType(options.mimeType)
xhr.open(options.method || 'GET', url, true, options.user || null, options.password || null)
var headers = options.headers || {}
for (var header in headers) {
xhr.setRequestHeader(header, headers[header])
}
xhr.onload = function() {
(((xhr.status / 100)|0) === 2 ? resolve : reject)(xhr)
}
xhr.onerror = xhr.ontimeout = function() {
// status is 0 on timeout/error
reject(xhr)
}
xhr.send(options.body)
})
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.