开发者

How to load a script synchronously with RequireJS

I am using RequireJS in ASP.NET. There is a user control that includes a script file, and registers a startup script in order to initialize itself. Here's the generated code:

<script src="script/UserControls/myctrl.js" type="text/javascript"></script>

...

<script type="text/javascript">
function myCtrl1_init() {
    // initialize control
    // *JS ERROR* because myctrl.js hasn't run yet
    Sys.Application.remove_load(myCtrl1_init);
}
Sys.Application.add_load(myCtrl1_init);
</script>

The myctrl.js file looks something like this:

require(['script/dep1', 'script/dep2'], function(dep1, dep2) {      
    MyCtrl = function () {
    };
    MyCtrl.init = function(id) {
        dep1.doSomething();
    }
};

So, the problem is that startup script runs before the myctrl.js file has had a chance to run. Currently, the require call uses a callback function, which obviously doesn't run until later, and this is the problem... the script returns and the browser continues to the startup script before MyCtrl has been creat开发者_StackOverflow中文版ed.

I have tried simply calling require(['script/dep1', 'script/dep2']); at the top of the file, but that doesn't block either, and the script fails because the dependencies haven't loaded yet. The dependencies are modules, by the way, e.g. they use define().

Is there a way to load a script file synchronously with RequireJS? The API documentation says that "Using RequireJS in a server-side JavaScript environment that has synchronous loading should be as easy as redefining require.load()", but I have no idea what this means.

Any suggestions?


I assume the script tag for require.js is above the contents you mention. If so, then I would convert myctrl.js to be a module (use "define('myctrl', ....)" instead of "require(.." inside it), then in the inline script tag content do something like:

<script type="text/javascript">
require(["myctrl"], function () {
    function myCtrl1_init() {
        // initialize control
        // *JS ERROR* because myctrl.js hasn't run yet
        Sys.Application.remove_load(myCtrl1_init);
    }
    Sys.Application.add_load(myCtrl1_init);
});
</script>

I am not familiar with ASP.NET, so I am not sure if it is OK to do those Sys.Application calls in a callback that may fire after DOMContentLoaded, but the above is the general idea.

There is no way to synchronously load a script in the browser with RequireJS, a callback method like above needs to be used. The require.load() information was for developers that want to make RequireJS adapters that run in sync environments (basically non-browser JS environments).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜