Skip to content

Commit

Permalink
Move to using mutation observing to reduce page overhead (#985)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonathanKingston authored Nov 3, 2021
1 parent b866bc3 commit 59ece79
Showing 1 changed file with 28 additions and 14 deletions.
42 changes: 28 additions & 14 deletions Core/contentblocker.js
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,7 @@ _utf8_encode : function (string) {

// public
function shouldBlock(trackerUrl, type) {
seenUrls.add(trackerUrl)
let startTime = performance.now()

if (!blockingEnabled) {
Expand Down Expand Up @@ -589,14 +590,18 @@ _utf8_encode : function (string) {
return false
}

const seenUrls = new Set()
function hasNotSeen(url) {
return !seenUrls.has(url)
}

function processPage() {
[].slice.apply(document.scripts).forEach(function(el) {
[...document.scripts].filter(hasNotSeen).forEach((el) => {
if (shouldBlock(el.src, 'SCRIPT')) {
duckduckgoDebugMessaging.log("blocking load")
}

});
[].slice.apply(document.images).forEach(function(el) {
[...document.images].filter(hasNotSeen).forEach((el) => {
// If the image's natural width is zero, then it has not loaded so we
// can assume that it may have been blocked.
if (el.naturalWidth === 0) {
Expand All @@ -605,25 +610,34 @@ _utf8_encode : function (string) {
}
}
});
[].slice.apply(document.querySelectorAll('link')).forEach(function(el) {
[...document.querySelectorAll('link')].filter(hasNotSeen).forEach((el) => {
if (shouldBlock(el.href, 'LINK')) {
duckduckgoDebugMessaging.log("blocking load")
}
});
[].slice.apply(document.querySelectorAll('iframe')).forEach(function(el) {
if (shouldBlock(el.src, 'IFRAME')) {
duckduckgoDebugMessaging.log("blocking load")
}
[...document.querySelectorAll('iframe')].filter(hasNotSeen).forEach((el) => {
if (shouldBlock(el.src, 'IFRAME')) {
duckduckgoDebugMessaging.log("blocking load")
}
});
scheduleProcessPage()
}

var interval = 1
function scheduleProcessPage() {
interval *= 2
setTimeout(processPage, interval * 1000)

function debounce(func, wait) {
let timeout
return function () {
clearTimeout(timeout)
timeout = setTimeout(() => {
func.apply(this, arguments)
}, wait)
}
}

const observer = new MutationObserver(debounce((mutations, o) => {
processPage()
}, 100))
const rootElement = document.body || document.documentElement
observer.observe(rootElement, { childList: true, subtree: true });

// Init
(function() {

Expand Down

0 comments on commit 59ece79

Please sign in to comment.