0

I'm trying to make a website mobile-friendly. One of the steps is to hide the right column, which has ads and non-essential data. In the CSS, I have something like this:

@media only screen {
    @media handheld or (max-width: 768px) {
        #column_right {display:none}
    }
}

The problem is that the right column contains javascript to display ads, which will still be executed. This is bad for 2 reasons: 1. It slows down the loading of the page. 2. It is against the ad networks' TOS (because the view is still registered, even though the visitor doesn't see an ad)

How would I prevent the code in the hidden column from being executed?

Edited to add: Here is one of the javascript code blocks that I need to disable:

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- removed ad block name -->
<ins class="adsbygoogle"
     style="display:inline-block;width:160px;height:600px"
     data-ad-client="removed"
     data-ad-slot="removed"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
4

3 回答 3

0

不,如果您在页面上编写代码,您无法阻止加载代码。因为 Javascript/Jquery 代码是在 DOM 处于就绪状态时呈现的。

visibility您可以通过检查属性来阻止执行代码块。

像那样:

var theCSSprop = getComputedStyle( document.querySelector("#column_right") ).visibility

if(theCSSprop != "hidden"){
  // write your code which you want to prevent 
}

如果您想提高页面性能,而不是将 JavaScript 移动到页面底部而不是将它们放在头部/顶部。

读这个

查看实时示例

于 2013-11-01T04:46:08.487 回答
0

如果你使用 jQuery,你可以检查元素是否可见。 http://api.jquery.com/visible-selector/

于 2013-11-01T04:20:07.407 回答
0

我建议使用 jQuery 进行$(window).width()检查。您可以调用它$(document).ready()并收听$(window).resize().

如果您正在收听调整大小,您当然想要执行以下操作:

var MAX_WINDOW_WIDTH = 768;

checkWindowSize();

$(window).resize(checkWindowSize);

function checkWindowSize(){
    if ($(window).width() < MAX_WINDOW_WIDTH && $('#column_right').size() > 0){
        $('#column_right .ad-block').remove();
    }
    if ($(window).width() > MAX_WINDOW_WIDTH && $('#column_right').size() == 0){
        $('#column_right').append('[some HTML ad code here]');
    }
});
于 2013-11-01T04:30:16.603 回答