JavaScript 什么时候计算一个函数?是在页面加载时还是在调用函数时?
之所以这么问,是因为我有如下代码:
function scriptLoaded() {
// one of our scripts finished loading, detect which scripts are available:
var jQuery = window.jQuery;
var maps = window.google && google.maps;
if (maps && !requiresGmaps.called) {
requiresGmaps.called = true;
requiresGmaps();
}
if (jQuery && !requiresJQuery.called) {
requiresJQuery.called = true;
requiresJQuery();
}
if (maps && jQuery && !requiresBothJQueryGmaps.called) {
requiresBothJQueryGmaps.called = true;
requiresBothJQueryGmaps();
}
}
// asynch download of script
function addScript(url) {
var script = document.createElement('script');
script.src = url;
// older IE...
script.onreadystatechange=function () {
if (this.readyState == 'complete') scriptLoaded.call(this);
}
script.onload=scriptLoaded;
document.getElementsByTagName('head')[0].appendChild(script);
}
addScript('http://google.com/gmaps.js');
addScript('http://jquery.com/jquery.js');
// define some function dependecies
function requiresJQuery() { // create JQuery objects }
function requiresGmaps() { // create Google Maps object, etc }
function requiresBothJQueryGmaps() { ... }
我想做的是执行我的 JavaScript 的异步下载,并尽早开始执行这些脚本,但我的代码依赖于脚本明显下载和加载的时间。
当我尝试上面的代码时,我的浏览器似乎仍在尝试计算我的 require*
函数中的代码,甚至在这些函数被调用之前。它是否正确?还是我误解了我的代码有什么问题?
最佳答案
函数在调用时被评估。
例如
function test() {
window.foo = 'bar';
}
console.log(window.foo); // => undefined
test();
console.log(window.foo); // => bar
尽管test
在第一个 console.log
之前创建, window.foo
直到 test
才被填充实际上被调用了。
如果您的 requires*
函数挂起/阻塞,那么您需要显示这些代码(为什么不提供有问题的代码的源代码?)
编辑:
目前,当您附加已加载的 <script>
时,您的网站对我来说是空白的到 <head>
.
无论如何,一个快速的解决方法是将您想要的脚本放在页面底部附近,</body>
之前。 , 因为只有 <head>
中的脚本将在加载时完全阻塞页面。
有一些优雅的方法可以延迟加载资源,但是,为了保持简单..
<script type="text/javascript" src="http://path/to/jquery.js"></script>
<script type="text/javascript">
requiresJQuery(); // jQuery is available at this point
</script>
</body>
重点是,自<script>
放置在您的主要元素之后,DOM 元素将在浏览器开始下载您的其他库之前可用(并可能加载)。
关于JavaScript:JavaScript 什么时候评估一个函数,onload 或什么时候调用函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2812441/