balsamine.2017-2018
clone your own copy | download snapshot

Snapshots | iceberg

Inside this repository

stories.js
application/javascript

Download raw (2.6 KB)

;(function(window, document) {
    'use strict';

    // http://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery
    function callAjax(url, callback){
        var xmlhttp;
        // compatible with IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
        xmlhttp.withCredentials = true;
        xmlhttp.onreadystatechange = function(){
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
                callback(xmlhttp.responseText);
            }
        }
        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

    // loads stories
    window.addEventListener("load", function () {
        var stories = document.querySelectorAll('article[data-src]'),
            loadedstories = 0;

        for (var i = 0, l = stories.length; i < l; i ++) {
            (function () {
            var story = stories[i];
            var src = story.dataset.src;
            story.addEventListener("storyloaded", function () {
                loadedstories++;
                
                if (loadedstories == stories.length) {
                    var e = new Event("storiesloaded");
                    document.dispatchEvent(e);
                }
            });

            callAjax(src, function(data) {
                story.innerHTML = data;

                var e = new Event("htmlinjected");
                story.dispatchEvent(e);

                var images = story.querySelectorAll('img'),
                    storyImageCount = images.length,
                    storyImagesLoaded = 0;

                function storyLoaded () {
                    var e = new Event("storyloaded");
                    story.dispatchEvent(e);
                }

                function imageLoaded () {
                    var e = new Event("imageloaded");
                    story.dispatchEvent(e);
                }

                if (images.length > 0) {
                    story.addEventListener("imageloaded", function () {
                        storyImagesLoaded++;
                        if (storyImagesLoaded >= storyImageCount) {
                            storyLoaded();
                        }
                    })
                } else {
                    storyLoaded();
                }

                for (var i=0; i < images.length; i++) {
                    if (images[i].complete) {
                        imageLoaded();
                    } else {
                        images[i].addEventListener("load", imageLoaded);
                    } 
                }
            });
            })();
        }
    });
})(window, document);