Skip to content

Instantly share code, notes, and snippets.

@igrigorik
Forked from slightlyoff/connectionchange.js
Last active December 24, 2015 10:09
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 igrigorik/6781961 to your computer and use it in GitHub Desktop.
Save igrigorik/6781961 to your computer and use it in GitHub Desktop.
Based on earlier iterations in https://gist.github.com/slightlyoff/4755944
class ConnectionInfo {
constructor(media="unknown",
className="unknown",
classId=0) {
this.media = media;
this.className = className;
this.classId = classId;
}
}
var typeGenerator = function(type) {
var id = 0;
return function(className) {
return new ConnectionInfo(type, className, ++id);
};
};
var e = typeGenerator("ethernet");
var w = typeGenerator("wifi");
var c = typeGenerator("cellular");
var connectionClasses = {
ethernet: [
e("10"),
e("100"),
e("1000"),
e("10000"),
e("100000")
],
wifi: [
w("a"),
w("b"),
w("g"),
w("n"),
w("ac"), // draft
w("ad") // future
],
cellular: [
c("2"),
c("2.5"), // GPRS
c("2.75"), // EDGE
c("3"), // UMTS, CDMA2000 1X
c("3.5"), // HSPA, EV-DO
c("3.75"), // HSPA+, EV-DO Advanced
c("3.9"), // LTE
c("4") // LTE Advanced
],
bluetooth: [1, 1.1, 1.2, 2.0, 2.1, 3.0]
};
// Example usage:
// check current connection type, adjust logic
if(navigator.connectionInfo.media == "wifi") { ... }
// subscribe to connection type updates
window.addEvenListener("connectionchange", function(e) {
var ci = navigator.connectionInfo;
// Adapt based on current connection type ...
// E.g. http://developer.android.com/training/efficient-downloads/connectivity_patterns.html
switch (ci.media) {
case "wifi":
runBackgroundUpdate();
case "cellular":
if (ci.classId > 5) { // worse than 4G
lowerPrefetchSize();
break;
}
default:
// ...
break;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment