Javascript仅适用于重新加载页面

时间:2017-08-22 23:57:07

标签: javascript jquery

https://bm-translations.de/dolmetscher-franzoesisch-deutsch.php上,您可以看到标题的效果与此处不同:https://bm-translations.de

我猜起JS出于某种原因不能正常工作。但奇怪的是重新加载页面(strg + F5)它的工作。这有什么不对吗?

我首先加载Jquery,然后加载我自己的JS。

2 个答案:

答案 0 :(得分:2)

这很可能是竞争条件。你可能在DOM有机会加载之前运行你的javascript。它在第二次重新加载时的工作原因是浏览器正在使用脚本的缓存版本。

有几种方法可以解决这个问题:

确保脚本代码没有async属性。这告诉他们允许他们按照他们喜欢的任何顺序加载,这样你的脚本可能会在jQuery有机会加载之前加载。

确保您的脚本顺序正确。最简单的方法是将脚本移动到正文的底部,以便浏览器最后加载它。确保你的脚本遵循任何依赖脚本,例如jQuery。

    <script src="jquery.js"></script>
    <script src="myscript.js"></script>
</body>

另一种选择是使用“就绪”事件。由于您正在使用JQuery,因此只需将函数包装在带有回调函数的jQuery对象中即可访问它。

console.log('this will run before the DOM is loaded');

// wait for DOM to load inside jquery callback
$(function() {
    console.log('this will run after the DOM has loaded');
});

console.log('this will also run before the DOM is loaded');

上述代码的输出如下:

'this will run before the DOM is loaded'
'this will also run before the DOM is loaded'
'this will also run before the DOM is loaded'

答案 1 :(得分:1)

因为您已将async属性添加到jquery脚本标记。 如果某些其他脚本依赖于jquery,则不能在此处使用async属性。

https://bm-translations.de/dolmetscher-franzoesisch-deutsch.php

中的

<script async src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script async src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>
https://bm-translations.de

中的

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script async="" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.lazyload/1.9.1/jquery.lazyload.min.js"></script>

more about async attribute.

相关问题