-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathcharset.js
50 lines (40 loc) · 1.34 KB
/
charset.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
/**
* @file rule: charset
* @author nighca<[email protected]>
*/
module.exports = {
name: 'charset',
desc: '<meta charset> recommended.',
lint: function (getCfg, document, reporter) {
var head = document.querySelector('head');
if (!head || !getCfg(head)) {
return;
}
var charsetMeta = head.querySelector('meta[charset]');
if (!charsetMeta) {
reporter.warn(head.startIndex, '006', '<meta charset> recommended.');
}
else if (charsetMeta !== head.firstElementChild) {
reporter.warn(charsetMeta.startIndex, '007', '<meta> charset should be the first element child of <head>.');
}
},
format: function (getCfg, document, options) {
var head = document.querySelector('head');
if (!head || !getCfg(head)) {
return;
}
var charsetMeta = document.querySelector('meta[charset]');
if (!charsetMeta) {
charsetMeta = document.createElement('meta');
charsetMeta.setAttribute('charset', 'utf-8');
}
if (charsetMeta !== head.firstElementChild) {
if (head.firstElementChild) {
head.insertBefore(charsetMeta, head.firstChild);
}
else {
head.appendChild(charsetMeta);
}
}
}
};