setTimeout不允许我附加到innerHTML

时间:2018-11-05 14:19:20

标签: javascript html

我怀疑我的代码的setTimeout部分应该受到指责,但是我可以毫无问题地附加到DOM的document.body部分。我在做什么错了?

let adblock = document.getElementById(`adblock`);
    
    let fake_ad = document.createElement("div");
    fake_ad.innerHTML = " ";
    // Hide it from viewport
    fake_ad.setAttribute("style", "top: -999px; position: fixed;");
    // Add some Adblock bait classes
    fake_ad.className = "adsbox ad-300x250 banner-ad";
    // Append the ad to DOM
    document.body.appendChild(fake_ad);
    // Wait 500ms for the adblocker to do its job
    window.setTimeout(function() {
    	if (fake_ad.offsetHeight === 0) {
    		// Add class .ab to body
    		document.body.classList.add("ab");
    		// For testing
    		console.log("Adblock is enabled!");
    		adblock.innerHTML = "present!";
    		document.body.innerHTML += "Adblock is enabled!";
    	} else {
    		// For testing
    		console.log("Adblock is disabled!");
    		document.body.innerHTML += "Adblock is disabled!";
    	}
    	// Remove the fake ad from DOM
    	document.body.removeChild(fake_ad);
    }, 500);
<!DOCTYPE html>
<html lang=en>

<head>
  <title>test</title>
</head>

<body>
  <p>Adblocking is <strong id="adblock"></strong></p>
</body>

</html>

2 个答案:

答案 0 :(得分:0)

可能在setTimeout内部执行的代码是在垃圾回收周期删除fake_ad之后执行的,因为任何活动函数都不会引用该代码。您可以尝试将fake_ad变量传递给setTimeout调用,因此该变量具有防止蜜蜂收集垃圾的引用:

window.setTimeout(function(fake_ad) {
...
}, 500, fake_ad);

答案 1 :(得分:0)

尝试包装您的JavaScript,以使其在窗口加载后运行。如果您事先尝试操作DOM,则这些对象将不存在。

类似的东西:

window.addEventListener('load', function() {
  code block here...
}

或者,您可以从脚本标签中删除async,并将其附加在结束<body>标签之后和结束<html>标签之前。

示例:https://jsfiddle.net/yLt6319m/2/