Execute javascript script after Require.js finishe

2019-04-02 16:48发布

问题:

I'm creating a Phonegap app. I'm using Require.js and am implementing Push Notification. In my index.html file I have:

<script data-main="js/app" src="js/require.js"></script>

<script type="text/javascript" src="js/app/index.js"></script>
<script type="text/javascript">
    app.initialize();
</script>

The app.js defines the base url for Require.js modules and initiates the router. Index.html defines the "deviceready" listener. The problem is that within index.js, I need to have accress to Require.js modules, such as Jquery. But for example, in index.js, if I do:

initialize: function() {

    require(["jquery"], function () {

    });
},

I get the error:

Uncaught Error: Script error for: jquery
http://requirejs.org/docs/errors.html#scripterror at file:///android_asset/www/js/require.js:8
Uncaught Error: Load timeout for modules: backbone
http://requirejs.org/docs/errors.html#timeout at file:///android_asset/www/js/require.js:8

I think this is because index.js is called whilst app.js is still setting up paths etc. I need index.js to execute after app.js is finished. I CANNOT use:

    $(document).ready(function() {
        app.initialize();
    });

because Jquery is loaded as a module so will throw an error. I also cannot load index.js as a module because of a problem I wrote about in another SO question here.

Any ideas what I can do?

回答1:

If you load your main file with a separate <script> tag rather than with data-main, then your configuration for RequireJS will run right away:

<script src="js/require.js"></script>
<script src="js/app.js"></script>

This may be problematic depending on what js/app.js contains. If it causes problems, then you can split this file into a) a file that contains only RequireJS's configuration (let's call it js/requirejs-config.js), b) the app proper (which would still be called js/app.js). So something like:

<script src="js/require.js"></script>
<script src="js/require-config.js"></script>
<script>
    require(["js/app"]);
</script>

Or you could possibly add a top-level deps field to your configuration like this deps: ["js/app"] so as to avoid needing the third <script> tag.



回答2:

I ran into the same issue with my cordova app on ios. The dynamic loading failed with the same error, though I have the same code running well on the browser.

My workaround is to first statically load the module, via defining shim.deps of the 'app' in data-main, so the module gets loaded initially via require. Subsequently it's then available when module is needed - require(["jquery"]) will then be ok.

Definitely want to get to the root of the problem though, but for now I can proceed.