all files / htmlcs/lib/rules/ script-in-tail.js

100% Statements 18/18
100% Branches 17/17
100% Functions 3/3
100% Lines 18/18
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 55 56 57 58                      103× 103×   103× 23×     80× 16×     16×         12×                 80× 36× 20×     16× 14×                    
/**
 * @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 (getCfg, document, reporter) {
        var html = document.querySelector('html');
        var body = document.querySelector('body');
 
        if (!(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 (!getCfg(script)) {
                return;
            }
 
            if (!isInTail(script)) {
                reporter.warn(
                    script.startIndex,
                    '023',
                    'JavaScript contents are recommended to be imported in the tail of <body>.'
                );
            }
        });
    }
 
};