-
Notifications
You must be signed in to change notification settings - Fork 8
/
script-in-tail.js
57 lines (45 loc) · 1.58 KB
/
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
55
56
57
/**
* @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>.'
);
}
});
}
};