JavaScript:JavaScript何时评估函数,onload或何时调用函数?

Ben*_*enj 2 javascript jquery google-maps asynchronous

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() { ... }
Run Code Online (Sandbox Code Playgroud)

我想要做的是执行我的JavaScript的异步下载,并尽早开始执行这些脚本,但我的代码依赖于脚本明显下载和加载的时间.

当我尝试上面的代码时,看起来我的浏览器仍在尝试在我的require*函数中评估代码,甚至在调用这些函数之前.它是否正确?或者我误解了我的代码有什么问题?

Mat*_*att 5

调用时会评估函数.

例如

function test() {
    window.foo = 'bar';
}

console.log(window.foo); // => undefined
test();
console.log(window.foo); // => bar
Run Code Online (Sandbox Code Playgroud)

即使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>
Run Code Online (Sandbox Code Playgroud)

关键是,由于它<script>是在主要元素之后放置的,因此在浏览器开始下载其他库之前,DOM元素将可用(并且可能已加载).