如何在JSP页面中使用Javascript停止HTML渲染?

时间:2015-12-12 18:55:29

标签: javascript html jsp

这个想法是,如果用户从中国访问我们的网站,我们必须阻止某些资产来提高我们的网站速度。 (例如,Facebook资源。我需要阻止他们甚至尝试加载,因为他们总是会被阻止回来)

需要注意的是,我必须在JavaScript (更新:请参阅底部编辑)中执行此操作,因为由于我们使用Akamai进行缓存,因此必须在客户端完成。

使用一些JSTL来考虑这个HTML:

<div class="num1">
  //some stuff like text and images
    <div class="num2">
        //a nested div with other stuff
      <c:if test="${varIsAlwaysTrue eq false}">
        <div class="num3">
        </div>
      </c:if>
    </div>
</div>

如何围绕使用JavaScript变量的IF语句? (该变量称为XY.isChina)

我真正能想到的就是scriptlet方法:(而不是&lt;%标签和Java代码,显然)

<script>
if (XY.isChina === false) {
</script>

<div class="num1">
  //some stuff like text and images
    <div class="num2">
        //a nested div with other stuff
      <c:if test="${varIsAlwaysTrue eq false}">
        <div class="num3">
        </div>
      </c:if>
    </div>
</div>


<script>
}
</script>

我几乎是积极的,不起作用。

这里游戏的目标是IF语句中没有任何内容加载。在页面上打孔是可以接受的,但是如果响应元素可以像对待它一样对待它(为了对齐目的)那么那就更好了。

有什么想法吗?

提前致谢。

编辑:我应该说我需要在客户端进行,而不是特别指定JavaScript。该变量已经在JavaScript中设置,但如果有其他客户端方法来执行此操作,那很好。 然而,我不能使用像jQuery这样的库。

2 个答案:

答案 0 :(得分:1)

从另一个角度看待它。为什么不隐藏这些部分XY.isChina == true而不是加载它们,如果这个条件为真,因为你的JSP在执行Javascript之前已经渲染了HTML。

<script>
if (XY.isChina === false) {
   document.getElementById( "numxyz" ).style.display = 'none';
}
</script>

答案 1 :(得分:1)

  

我需要阻止他们甚至尝试加载

听起来像试图圈出圆圈,因为

  

由于我们的缓存,它必须在客户端完成

因此,作为第一个(部分)结论,您似乎必须接受要加载的相关部分。

然后剩下的问题是避免显示恰好隐藏的内容(花费时间,对用户体验不利)。

所以解决方案可能是最初隐藏这些部分,然后只有在必须显示时才显示它们。在您给出的示例中,看起来像这样:

HTML:

<div class="num1 block-for-china"> <!-- note the dedicated class here -->
  //some stuff like text and images
    <div class="num2">
        //a nested div with other stuff
      <c:if test="${varIsAlwaysTrue eq false}">
        <div class="num3">
        </div>
      </c:if>
    </div>
</div>

CSS:

.block-for-china {
  display: none;
}

JS:

document.onload(function() {
  if (!XY.isChina) { // <-- up to you how to test this condition...
    var blockForChina = document.getElementsByClassName('block-for-china');
    for (var index in blockForChina) {
       blockForChina[index].style.display = 'inherit';
    }
  }
});