Angular + Requirejs - 加载顺序错误

Nic*_*own 2 javascript jquery asynchronous requirejs angularjs

我正在尝试使用requirejs加载angular和jquery.我能做的最好的是50%的时间都能正确加载,另一半我得到了错误No Module: mainApp

我假设这是基于requirejs异步加载脚本的速度打破一半的时间.

当它工作时,我看到"Hello World"测试(虽然我确实看到{{text}}在替换之前闪存,但我一直在阅读如何解决这个问题).剩下的时间我收到错误并且{{text}}只是停留在屏幕上.

Github Repo

Tree:

index.html
- js
    - libs
        require.js
    - modules
        mainApp.js
    main.js
Run Code Online (Sandbox Code Playgroud)

main.js

require.config({
  paths: {
    'jQuery': '//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min',
    'angular': '//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular',
  },
  shim: {
    'angular' : {'exports' : 'angular'},
    'jQuery': {'exports' : 'jQuery'}
  }
});

require(['jQuery', 'angular', 'modules/mainApp'] , function ($, angular, mainApp) {
  $(function () { // using jQuery because it will run this even if DOM load already      happened
    angular.bootstrap(document, ['mainApp']);
  });
});
Run Code Online (Sandbox Code Playgroud)

modules/mainApp.js

define(['angular'], function (angular) {
  return angular.module('mainApp' , []).controller('MainCtrl', ['$scope', function ($scope) {
      $scope.text = 'Hello World';
  }]);
});
Run Code Online (Sandbox Code Playgroud)

Relevant index.html

<head>
    <script src="js/libs/require.js" data-main="js/main"></script>
</head>
<body>
    <div ng-app="mainApp">
        <div ng-controller="MainCtrl">
            {{text}}
        </div>
    </div>
</body>
Run Code Online (Sandbox Code Playgroud)

Lim*_* H. 6

在引导应用程序之前,您可以使用domReady(UPDATED)来确保DOM已完全加载,即所有JS文件都在那里.

requirejs.config({
    paths: {
        jquery: '/path/to/jquery',
        angular: 'path/to/angular',
        domReady: '/path/tp/domReady'
    }, shim: {
        angular: {
            exports: 'angular'
        },  
    }   
});
define(['jquery', 'angular', 'modules/mainApp'], 
    function($, angular, 'mainApp') {
        // tell angular to wait until the DOM is ready
        // before bootstrapping the application
        require(['domReady'], function() {
            angular.bootstrap(document, ['mainApp']);
        }); 
});
Run Code Online (Sandbox Code Playgroud)

有关此问题的更多信息,请参阅RequireJS官方文档:

使用RequireJS可以足够快地加载脚本,以便在DOM准备好之前完成脚本.尝试与DOM交互的任何工作都应该等待DOM准备好.

这个技巧可以在这篇博客文章中找到.

编辑如果您按照博客文章的建议,请使用此domReady脚本而不是我之前发布的脚本:https://github.com/requirejs/domReady/blob/master/domReady.js.