Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [code]
- function () {
- function t(e) {
- (new Image).src = "http://xkcd.com/events/" + e
- }
- function n() {
- location.hash == "#verbose" && console.log.apply(console, arguments)
- }
- // This spreads requests over 8 subdomains
- var e = ["http://c0.xkcd.com", "http://c1.xkcd.com", "http://c2.xkcd.com", "http://c3.xkcd.com", "http://c4.xkcd.com", "http://c5.xkcd.com", "http://c6.xkcd.com", "http://c7.xkcd.com"];
- try {
- // This selects randomly between the subdomains above
- var r = e[Math.floor(Math.random() * e.length)],
- // These create a new event source to listen for a new comic
- i = r + "/stream/comic/time?method=EventSource",
- s = new EventSource(i);
- // This starts a connection to the event source
- n("connecting to event source:", i), s.addEventListener("open", function (e) {
- t("connect_start")
- }, !1), s.addEventListener("error", function (e) {
- n("connection error", e), t("connect_error")
- }, !1), s.addEventListener("comic/time/ping", n, !1), s.addEventListener("comic/time", n, !1);
- var o = !0;
- // If the event source spits out a response, parse it.
- // The event source is just a JSON file that includes what looks like a SHA1 hash that is used to construct the image's file name
- s.addEventListener("comic/time", function (e) {
- var t = JSON.parse(e.data),
- r = document.getElementById("comic").getElementsByTagName("img")[0],
- i = o ? 0 : Math.round(Math.random() * t.spread);
- n("waiting", i, "seconds before displaying comic", t.image), setTimeout(function () {
- // This changes the image on the web page
- r.src = "http://imgs.xkcd.com/comics/time/" + t.image
- }, i * 1e3), o = !1
- // This basically just keeps checking for a new image, and if it finds one, loads it.
- // The timing of new images is entirely server-side, controlled by what JSON response the servers give.
- // As far as I can see, there is no way to speed things up, since the event responses are sent from the server.
- }, !1), s.addEventListener("comic/time/reload", function (e) {
- var r = Math.round(Math.random() * 55);
- n("reloading in", r + 5, "seconds"), setTimeout(function () {
- t("reloading"), setTimeout(function () {
- location.reload()
- }, 5e3)
- }, r * 1e3)
- }, !1)
- } catch (u) {
- t("js_error")
- }
- }();
- [/code]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement