等待没有锁定的延迟加载对象? [英] Waiting on Lazy Loaded objects without lockup?

查看:81
本文介绍了等待没有锁定的延迟加载对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经有可以按要求懒加载脚本的代码.我的问题现在是等待执行某些代码,直到对象可用为止.我不能使用setTimeout(),因为它不会阻止执行.

I already have code which lazy loads scripts on request. My issue now is waiting to execute certain code until the object becomes available. I can't use a setTimeout() because it does not block execution.

那么在不锁定浏览器的情况下等待"加载的好方法是什么?

So what is a good way to 'wait' for a load, without locking the browser?

同样,不能使用原始的setTimeout().

Again, can't use raw setTimeout().

推荐答案

假设您控制脚本的内容,则可以在懒加载的脚本的底部放置一些要执行的代码,以在主页上指示该脚本已加载.例如,在您的页面中,您可以执行以下操作:

Assuming you control the contents of your script, you can put some code to execute at the bottom of your lazy loaded script to indicate to the main page that the script has loaded. For example, in your page you can do something like this:

var loadingScripts = 0;
var loadScript = function() {
    // Do what you need to do to load the script...

    loadingScripts++;
}

var loadedScript = function() {
    loadingScripts--;
    if (loadingScripts == 0) {
        // Kick off execution of code that requires the lazy loaded scripts.
    }
}

然后在您的脚本中,将此代码添加到底部:

Then in your script, you'd add this code to the bottom:

loadedScript();

您可以使用数组而不是整数来增加示例的趣味性(以跟踪已加载的特定脚本).您也可以使用一个对象来将特定的函数调用与特定脚本的完成关联起来.我的示例很简单,但请问是否要我展示如何扩展代码.

You can spice this example up with an array instead of an integer (to keep track of which specific scripts have loaded). You could also use an object instead to associate particular function calls with the completion of particular scripts. I kept my example simple, but ask if you want me to show how to do extend the code.

这里是如何使用回调在加载脚本后继续执行特定代码的方法(同样,假设您自己控制脚​​本).

Here is how you can use a callback to continue execution of specific code upon loading of a script (again, assuming you control the scripts themselves).

var scriptCallbacks = {}
var loadScript = function(scriptname, callback) {
    // Do what you need to load scriptname

    scriptCallbacks[scriptname] = callback;
}

var loadedScript = function(scriptname) {
    (scriptCallbacks[scriptname])();
}

然后,当您要加载脚本时,可以执行以下操作……

Then when you want to load a script, you do something like this...

var callback = function() {
    // Write exactly what you want executed once your script is loaded
}

loadScript("MyScript.js", callback);

再次,在您的延迟加载脚本中,只需将此代码添加到底部,以通知您的回调触发:

And again, in your lazy loaded script, just add this code to the bottom to inform your callback to fire:

loadedScript("MyScript.js");

这篇关于等待没有锁定的延迟加载对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆