简单的网页无图模式
当前为
// ==UserScript==
// @name 无图模式
// @namespace
// @include *://movie.douban.com
// @include *://movie.douban.com/*
// @version 0.1.7
// @description 简单的网页无图模式
// @author ymzhao
// @namespace
// ==/UserScript==
;
(function() {
'use strict';
const clearedTag = '#';
// 清理图片src
let clearImgs = function(source) {
let elements = document.getElementsByTagName("img");
const count = elements.length;
let notNull = 0;
Array.prototype.forEach.call(elements, function (element) {
if(element.src != clearedTag) {
element.src = clearedTag;
notNull++;
}
});
console.log('clear: source = ' + source + ', count = ' + count + ', dealed = ' + notNull);
}
// 定时器
let interval = window.setInterval(function(){
if(!isImgsAllCleared) {
clearImgs('interval');
}
},200);
// 清楚定时器
window.setTimeout(function(){
clearInterval(interval);
},1500);
// 初次清除图片
clearImgs('first');
// 新增DOM时,清除图片
document.addEventListener('DOMNodeInserted', throttle(function() {
if(!isImgsAllCleared) clearImgs('DOM Inserted');
}, 200));
/**
* 新图判断
*/
function isImgsAllCleared() {
let elements = document.getElementsByTagName("img");
if(elements.length == 0) return true;
return Array.prototype.every.call(elements, function (element) {
element.src = clearedTag;
});
}
/**
* 节流
*
* @param fn {Function} 实际要执行的函数
* @param delay {Number} 执行间隔,单位是毫秒(ms)
*
* @return {Function} 返回一个“节流”函数
*/
function throttle(fn, threshhold) {
// 记录上次执行的时间
var last
// 定时器
var timer
// 默认间隔为 250ms
threshhold || (threshhold = 250)
// 返回的函数,每过 threshhold 毫秒就执行一次 fn 函数
return function () {
// 保存函数调用时的上下文和参数,传递给 fn
var context = this
var args = arguments
var now = +new Date()
// 如果距离上次执行 fn 函数的时间小于 threshhold,那么就放弃
// 执行 fn,并重新计时
if (last && now < last + threshhold) {
clearTimeout(timer)
// 保证在当前时间区间结束后,再执行一次 fn
timer = setTimeout(function () {
last = now
fn.apply(context, args)
}, threshhold)
// 在时间区间的最开始和到达指定间隔的时候执行一次 fn
} else {
last = now
fn.apply(context, args)
}
}
}
})();