Code coverage report for htmlcs/lib/rules/script-in-tail.js

Statements: 100% (16 / 16)      Branches: 94.12% (16 / 17)      Functions: 100% (3 / 3)      Lines: 100% (16 / 16)      Ignored: none     

All files » htmlcs/lib/rules/ » script-in-tail.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54          1             37 37   37 36     1 8     8         4       4 4 2       2     1 8 6                    
/**
 * @file rule: script-in-tail
 * @author nighca<nighca@live.cn>
 */
 
module.exports = {
 
    name: 'script-in-tail',
 
    desc: 'All javascript contents are recommended to be imported in the tail of <body>.',
 
    lint: function (enable, document, reporter) {
        var html = document.querySelector('html');
        var body = document.querySelector('body');
 
        if (!enable || !(html  || body)) {
            return;
        }
 
        var isInTail = function (element) {
            var tagName = element.tagName;
 
            // should: no parent, or parent is <html>, or parent is <body>
            if (
                document.children.indexOf(element) < 0
                && (!html || html.children.indexOf(element) < 0)
                && (!body || body.children.indexOf(element) < 0)
            ) {
                return false;
            }
 
            // should: no followed elements unless with the same tag
            while (element = element.nextElementSibling) {
                if (element.tagName !== tagName) {
                    return false;
                }
            }
 
            return true;
        };
 
        document.querySelectorAll('script:not([type]), script[type="text/javascript"]').forEach(function (script) {
            if (!isInTail(script)) {
                reporter.warn(
                    script,
                    '023',
                    'Javascript contents are recommended to be imported in the tail of <body>.'
                );
            }
        });
    }
 
};