javascript - 在 AngularJS 服务中使用 window.onload

标签 javascript angularjs onload

我正在使用 AngularJS 1.6 创建一个依赖于某些图像的游戏。该游戏在很大程度上与 Angular 是分开的,并在任何 Controller 运行之前由服务实例化。我希望游戏由服务实例化,以便我可以将其公开给其他 Controller ,这些 Controller 以某种方式与游戏进行交互。我使用 $window.onload,但它仅在页面首次加载时起作用。当我刷新页面时,该事件不会触发,可能是因为浏览器正在从缓存中获取图像。

我考虑过使用 document.ready,但是当图像加载速度不够快时,这有时会导致问题。

我尝试过 jQuery、vanilla JS 和 Angular 的语法:

$(window).on('load', function() {});
$window.onload = function();
angular.element($window).on('load', function() {});

如有任何建议,我们将不胜感激。这就是我的代码的基本样子。

// Game Service (game state, game logic and game loop)
gameApp.service('theGame', function($log, $document, $window, 
$location, $timeout, $interval) {


    $window.onload = function() {
        // Initialize a new Game object
        var game = new Game();
        game.initGame();
    };

});

最佳答案

window.onload 放入 AngularJS 服务中就本末倒置了。 AngularJS 在 onload 事件之后加载。

相反,使用angular.element加载游戏,然后手动引导AngularJS:

angular.element(function() {
    var game = new Game();
    game.initGame();
    angular.module("myApp").value("theGame", game);
    angular.bootstrap(document, ['myApp']);
});

为避免自动初始化,请记住省略 ng-app 指令

Manual Initialization

If you need to have more control over the initialization process, you can use a manual bootstrapping method instead.

You should call angular.bootstrap() after you've loaded or defined your modules. You cannot add controllers, services, directives, etc after an application bootstraps.

— AngularJS Developer Guide - Bootstrap (Manual Initialization)

注:angular.element(f)是 angular.element(document).ready(f) 的别名 1

关于javascript - 在 AngularJS 服务中使用 window.onload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43877226/

相关文章:

javascript - 为什么我的 React Web App 在某些移动设备上看起来有很大不同?

javascript - 我可以使用 Materialise 在 View 中处理多个 .html 吗?

javascript - 如何首先加载动态插入的 img

javascript - 按顺序加载图像列表

javascript - angularjs 类不工作

JavaScript - 动态 SVG - onload 属性 - 未触发事件

javascript - 仅当 react.js 中的条件为真时才发送 Prop

Javascript 在 JSON 中检查最新版本的操作系统

javascript - 解码json代码时出错

javascript - 将 lodash 与 Angularjs 结合使用