Skip to content

Instantly share code, notes, and snippets.

@cwchentw
Last active October 11, 2020 05:44
Show Gist options
  • Save cwchentw/d5391905677cb245d7e5596f0681e677 to your computer and use it in GitHub Desktop.
Save cwchentw/d5391905677cb245d7e5596f0681e677 to your computer and use it in GitHub Desktop.
Boilerplate for Cross-browser Scripting in Vanilla JavaScript
function ie9 () {
let div = document.createElement("div");
div.innerHTML = "<!--[if lte IE 9]><i></i><![endif]-->";
return div.getElementsByTagName("i").length == 1;
}
function getXHR() {
if (ie9()) {
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch { }
try {
return new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch { }
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch { }
return null;
}
return new XMLHttpRequest();
}
let xhr = getXHR();
if (!xhr) {
/* You should always check whether `xhr` object is null.
Write some code to handle such condition properly. */
// return;
}
xhr.onreadystatechange = function () {
if (4 === xhr.readyState) {
if (200 === xhr.status) {
/* Implement your code here. */
}
else {
/* Any HTTP status other than 200. */
}
}
}
if (!ie9()) {
xhr.onerror = function () {
/* Write code to handle error condition.
The event is only valid on IE 10 or above. */
};
}
/* Modify the code here to fit your own condition. */
xhr.open("POST", `https://example.com/path/to/post/`);
/* JSON is the de facto standard format for Ajax events.
You may not need to modify anything here. */
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
/* Modify the code here to fit your own condition. */
let data = "";
if (ie9()) {
setTimeout(function () {
xhr.send(JSON.stringify({ data: data }));
}, 0);
}
else {
xhr.send(JSON.stringify({ data: data }));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment