SlideShare a Scribd company logo
Lazy Loading Techniques
Introduction

Nir Kaufman
nirkaufman@gmail.com

AngularJS infrastructures - lazy loading
techniques:
1. Introducing the lazy loading challenges with
AngularJS
2. Review a working demo project

nirkaufman@gmail.com
overview

AngularJS encourage us to break our code
into smaller pieces.

Modules
services
directives

controllers
filters

constants

nirkaufman@gmail.com
overview

Separating your code into multiple files considered
a best practice when building large apps with
angular.
Angular seed project:
❖

js/

angular.module('myApp.controllers', []).
■
■
■
■

❖

controllers.js
services.js
directives.js
filters.js

partials/
■ partial1.html
■ partial2.html

controller('MyCtrl1', function() {
})
.controller('MyCtrl2', function() {
});

nirkaufman@gmail.com
overview

We can define our modules as dependencies:
angular.module('myApp',['ngRoute',
'myApp.filters',
'myApp.services',
'myApp.directives',
'myApp.controllers',
’ngRoute’,
’ngResource’,
’ui.bootstrap’,
]).

nirkaufman@gmail.com
overview

but we must load all of our resources ahead:
<script src="lib/angular.js"></script>
<script src="lib/angular-route.js"></script>
<script src="js/app.js"></script>
<script src="js/services.js"></script>
<script src="js/controllers.js"></script>
<script src="js/filters.js"></script>
<script src="js/directives.js"></script>
………………..
<script src="lib/angular-resource.js"></script>
<script src="lib/angular-bootstrap.js"></script>
<script src="lib/underscore.js"></script>
nirkaufman@gmail.com
overview

All components must register against our module
on bootstrap. otherwise we can't use them.
Error: Argument ‘myController’ is not a function, got undefined

register
Lazy Loading Angular components

nirkaufman@gmail.com
solution

We need to answer those 3 questions in order to
solve this challenge:
● How to lazy load scripts async ?
● How to register our components against
our module after bootstrap?
● When & where the actual loading occurs?

nirkaufman@gmail.com
loading

RequireJS provides a clean way to load and
manage dependencies for our applications.
<script data-main="main" src="require.js"></script>
define(function () {
// module code
})
require([‘module’], function (module) {
// use this module
})

http://requirejs.org/
nirkaufman@gmail.com
register

Components register against the module in the
config phase using providers.
For instance, we can register our controller
manually using the ‘$controllerProvider’:
angular.module('moduleName', [])
.config(function($controllerProvider) {
$controllerProvider.register('Ctrl', function () {
// controller code
})
});

nirkaufman@gmail.com
register

All components can be registered with their
matching provider methods:
// services can register with $provide
$provide.service()
$provide.factory(),
$provide.value(),
$provide.constant(),
// other components use specific providers
$controllerProvider.resgister()
$animateProvider.resgister()
$filterProvider.resgister()
$compileProvider.directive()

nirkaufman@gmail.com
register

we need to hold a reference to this provider in
order to use it later in our code:
var app = angular.module('moduleName', [])
.config(function($controllerProvider) {
app.loadController = $controllerProvider.register;
})
});

app.loadController(‘someCtrl’, function ($scope) {})

nirkaufman@gmail.com
when to load

Where in the application should the actual loading
take place?

● when routing to a view - $routeProvider
● when loading content - <ng-include>
● in response to event - like click or hover

nirkaufman@gmail.com
routing

The route object contain a ‘resolve’ property that
can accept a map of promises and wait for them to
resolve before performing the route
angular.module('moduleName', [])
.config(function($routeProvider) {
$routeProvider.when('/', {
templateUrl: 'view.html',
controller : 'controller.js',
resolve : // promise
})
})
});

nirkaufman@gmail.com
routing

If every view managed by a controller we can
reflect that in our project structure by packing them
together & come up with naming conventions:
❖ views

➢ view-name
■ view-name.html
■ view-name.js

.controller(‘viewNameCtrl’, ….

➢ another-view
■ another-view-name.html
■ another-view-name.js

nirkaufman@gmail.com
events

We can load our dependencies as a reaction to an
event.
we can be creative and load our resources
depending on the user behaviour:
● load only when a user start to fill a form
● load by mouse position
● load when a response comming back from
the server

nirkaufman@gmail.com
modules

What about module loading?
ocLazyLoad is probably the best solution for lazy
loading angular modules (for now):
● Dependencies are automatically loaded
● Debugger like (no eval code)
● The ability to mix normal boot and load on demand
● Load via the service or the directive
● Use your own async loader (requireJS, script.js ...)

https://github.com/ocombe/ocLazyLoad
nirkaufman@gmail.com
summary

Lazy loading in Angular can be achived today with
minimum effort.
to keep our loading infrastructure flexible:
1. keep the loading logic in separated services
this will make our life easier when this feature will
be officially supported
2. use naming conventions
this way developers can integrate more easily
when moving between projects
nirkaufman@gmail.com
summary

Thank You!
Demo project source code:
https://github.com/nirkaufman/lazyLoadingDemo

nirkaufman@gmail.com

More Related Content

What's hot (20)

Enterprise Software Architecture styles
Enterprise Software Architecture styles
Araf Karsh Hamid
 
Introduction to Apache Synapse
Introduction to Apache Synapse
Hiranya Jayathilaka
 
Full stack development
Full stack development
Arnav Gupta
 
Gaganjot Kaur- The Nx Workspace.docx
Gaganjot Kaur- The Nx Workspace.docx
Gaganjot kaur
 
초심자를 위한 도커 소개 및 입문
초심자를 위한 도커 소개 및 입문
Daniel Seo
 
Jetpack Navigation Component
Jetpack Navigation Component
James Shvarts
 
Android Navigation Component
Android Navigation Component
Łukasz Ciupa
 
Best Practices for Middleware and Integration Architecture Modernization with...
Best Practices for Middleware and Integration Architecture Modernization with...
Claus Ibsen
 
[Foss4 g2014 korea] qgis를 플랫폼으로 한 파이썬기반 공간통계 구현 사례
[Foss4 g2014 korea] qgis를 플랫폼으로 한 파이썬기반 공간통계 구현 사례
BJ Jang
 
Introducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemash
Steven Smith
 
Introduction to Swagger
Introduction to Swagger
Knoldus Inc.
 
Spring Boot
Spring Boot
Jiayun Zhou
 
BDD WITH CUCUMBER AND JAVA
BDD WITH CUCUMBER AND JAVA
Srinivas Katakam
 
Getting Started With Cypress
Getting Started With Cypress
Knoldus Inc.
 
Cucumber ppt
Cucumber ppt
Qwinix Technologies
 
Vue JS Intro
Vue JS Intro
Muhammad Rizki Rijal
 
Distributed Applications with Apache Zookeeper
Distributed Applications with Apache Zookeeper
Alex Ehrnschwender
 
Applitools
Applitools
Rama Krishna Nakka
 
MEAN stack
MEAN stack
Iryney Baran
 
NestJS
NestJS
Wilson Su
 
Enterprise Software Architecture styles
Enterprise Software Architecture styles
Araf Karsh Hamid
 
Full stack development
Full stack development
Arnav Gupta
 
Gaganjot Kaur- The Nx Workspace.docx
Gaganjot Kaur- The Nx Workspace.docx
Gaganjot kaur
 
초심자를 위한 도커 소개 및 입문
초심자를 위한 도커 소개 및 입문
Daniel Seo
 
Jetpack Navigation Component
Jetpack Navigation Component
James Shvarts
 
Android Navigation Component
Android Navigation Component
Łukasz Ciupa
 
Best Practices for Middleware and Integration Architecture Modernization with...
Best Practices for Middleware and Integration Architecture Modernization with...
Claus Ibsen
 
[Foss4 g2014 korea] qgis를 플랫폼으로 한 파이썬기반 공간통계 구현 사례
[Foss4 g2014 korea] qgis를 플랫폼으로 한 파이썬기반 공간통계 구현 사례
BJ Jang
 
Introducing Domain Driven Design - codemash
Introducing Domain Driven Design - codemash
Steven Smith
 
Introduction to Swagger
Introduction to Swagger
Knoldus Inc.
 
BDD WITH CUCUMBER AND JAVA
BDD WITH CUCUMBER AND JAVA
Srinivas Katakam
 
Getting Started With Cypress
Getting Started With Cypress
Knoldus Inc.
 
Distributed Applications with Apache Zookeeper
Distributed Applications with Apache Zookeeper
Alex Ehrnschwender
 

Viewers also liked (20)

Angular js - 10 reasons to choose angularjs
Angular js - 10 reasons to choose angularjs
Nir Kaufman
 
AngularJS - Overcoming performance issues. Limits.
AngularJS - Overcoming performance issues. Limits.
Dragos Mihai Rusu
 
AngularJS performance & production tips
AngularJS performance & production tips
Nir Kaufman
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
Erik Guzman
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions
Arc & Codementor
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
Nir Kaufman
 
AngularJS Architecture
AngularJS Architecture
Eyal Vardi
 
Data Structures in javaScript 2015
Data Structures in javaScript 2015
Nir Kaufman
 
redux and angular - up and running
redux and angular - up and running
Nir Kaufman
 
Up & running with ECMAScript6
Up & running with ECMAScript6
Nir Kaufman
 
Solid angular
Solid angular
Nir Kaufman
 
Angular Pipes Workshop
Angular Pipes Workshop
Nir Kaufman
 
AngularJSの高速化
AngularJSの高速化
Kon Yuichi
 
How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!
Nir Kaufman
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introduction
Nir Kaufman
 
Angular2 workshop
Angular2 workshop
Nir Kaufman
 
Webstorm
Webstorm
Nir Kaufman
 
Webpack and angularjs
Webpack and angularjs
Nir Kaufman
 
AngularJS - Services
AngularJS - Services
Nir Kaufman
 
SPTECHCON - Get Some REST - Taking Advantage of the SharePoint 2013 REST API
SPTECHCON - Get Some REST - Taking Advantage of the SharePoint 2013 REST API
Eric Shupps
 
Angular js - 10 reasons to choose angularjs
Angular js - 10 reasons to choose angularjs
Nir Kaufman
 
AngularJS - Overcoming performance issues. Limits.
AngularJS - Overcoming performance issues. Limits.
Dragos Mihai Rusu
 
AngularJS performance & production tips
AngularJS performance & production tips
Nir Kaufman
 
Javascript Memory leaks and Performance & Angular
Javascript Memory leaks and Performance & Angular
Erik Guzman
 
29 Essential AngularJS Interview Questions
29 Essential AngularJS Interview Questions
Arc & Codementor
 
Redux with angular 2 - workshop 2016
Redux with angular 2 - workshop 2016
Nir Kaufman
 
AngularJS Architecture
AngularJS Architecture
Eyal Vardi
 
Data Structures in javaScript 2015
Data Structures in javaScript 2015
Nir Kaufman
 
redux and angular - up and running
redux and angular - up and running
Nir Kaufman
 
Up & running with ECMAScript6
Up & running with ECMAScript6
Nir Kaufman
 
Angular Pipes Workshop
Angular Pipes Workshop
Nir Kaufman
 
AngularJSの高速化
AngularJSの高速化
Kon Yuichi
 
How Angular2 Can Improve Your AngularJS Apps Today!
How Angular2 Can Improve Your AngularJS Apps Today!
Nir Kaufman
 
Angularjs - Unit testing introduction
Angularjs - Unit testing introduction
Nir Kaufman
 
Angular2 workshop
Angular2 workshop
Nir Kaufman
 
Webpack and angularjs
Webpack and angularjs
Nir Kaufman
 
AngularJS - Services
AngularJS - Services
Nir Kaufman
 
SPTECHCON - Get Some REST - Taking Advantage of the SharePoint 2013 REST API
SPTECHCON - Get Some REST - Taking Advantage of the SharePoint 2013 REST API
Eric Shupps
 
Ad

Similar to Angularjs - lazy loading techniques (10)

Step by Step Guide on Lazy Loading in Angular 11
Step by Step Guide on Lazy Loading in Angular 11
Katy Slemon
 
Implement lazy loading in your existing angular application (get a faster, be...
Implement lazy loading in your existing angular application (get a faster, be...
Katy Slemon
 
lazy loading
lazy loading
srinivaskapa1
 
angular
angular
srinivaskapa1
 
What is Lazy Loading
What is Lazy Loading
srinivaskapa1
 
New power of Angular2 Router
New power of Angular2 Router
Zhentian Wan
 
Angular Interview Question & Answers PDF By ScholarHat
Angular Interview Question & Answers PDF By ScholarHat
Scholarhat
 
Angular performance slides
Angular performance slides
David Barreto
 
[Srijan Wednesday Webinars] Developing Large Scale Applications in AngularJS
[Srijan Wednesday Webinars] Developing Large Scale Applications in AngularJS
Srijan Technologies
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
David Barreto
 
Step by Step Guide on Lazy Loading in Angular 11
Step by Step Guide on Lazy Loading in Angular 11
Katy Slemon
 
Implement lazy loading in your existing angular application (get a faster, be...
Implement lazy loading in your existing angular application (get a faster, be...
Katy Slemon
 
What is Lazy Loading
What is Lazy Loading
srinivaskapa1
 
New power of Angular2 Router
New power of Angular2 Router
Zhentian Wan
 
Angular Interview Question & Answers PDF By ScholarHat
Angular Interview Question & Answers PDF By ScholarHat
Scholarhat
 
Angular performance slides
Angular performance slides
David Barreto
 
[Srijan Wednesday Webinars] Developing Large Scale Applications in AngularJS
[Srijan Wednesday Webinars] Developing Large Scale Applications in AngularJS
Srijan Technologies
 
Angular Optimization Web Performance Meetup
Angular Optimization Web Performance Meetup
David Barreto
 
Ad

More from Nir Kaufman (14)

Angular Dependency Injection
Angular Dependency Injection
Nir Kaufman
 
Angular Prestige: Less-known API and techniques
Angular Prestige: Less-known API and techniques
Nir Kaufman
 
Angular CLI custom builders
Angular CLI custom builders
Nir Kaufman
 
Electronic music 101 for developers
Electronic music 101 for developers
Nir Kaufman
 
Nestjs MasterClass Slides
Nestjs MasterClass Slides
Nir Kaufman
 
Redux pattens - JSHeroes 2018
Redux pattens - JSHeroes 2018
Nir Kaufman
 
Angular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir Kaufman
Nir Kaufman
 
Boosting Angular runtime performance
Boosting Angular runtime performance
Nir Kaufman
 
Decorators in js
Decorators in js
Nir Kaufman
 
Styling recipes for Angular components
Styling recipes for Angular components
Nir Kaufman
 
Introduction To Angular's reactive forms
Introduction To Angular's reactive forms
Nir Kaufman
 
Angular redux
Angular redux
Nir Kaufman
 
Angular2 - getting-ready
Angular2 - getting-ready
Nir Kaufman
 
Angular js routing options
Angular js routing options
Nir Kaufman
 
Angular Dependency Injection
Angular Dependency Injection
Nir Kaufman
 
Angular Prestige: Less-known API and techniques
Angular Prestige: Less-known API and techniques
Nir Kaufman
 
Angular CLI custom builders
Angular CLI custom builders
Nir Kaufman
 
Electronic music 101 for developers
Electronic music 101 for developers
Nir Kaufman
 
Nestjs MasterClass Slides
Nestjs MasterClass Slides
Nir Kaufman
 
Redux pattens - JSHeroes 2018
Redux pattens - JSHeroes 2018
Nir Kaufman
 
Angular EE - Special Workshop by Nir Kaufman
Angular EE - Special Workshop by Nir Kaufman
Nir Kaufman
 
Boosting Angular runtime performance
Boosting Angular runtime performance
Nir Kaufman
 
Decorators in js
Decorators in js
Nir Kaufman
 
Styling recipes for Angular components
Styling recipes for Angular components
Nir Kaufman
 
Introduction To Angular's reactive forms
Introduction To Angular's reactive forms
Nir Kaufman
 
Angular2 - getting-ready
Angular2 - getting-ready
Nir Kaufman
 
Angular js routing options
Angular js routing options
Nir Kaufman
 

Recently uploaded (20)

Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Agentic AI: Beyond the Buzz- LangGraph Studio V2
Shashikant Jagtap
 
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
“Why It’s Critical to Have an Integrated Development Methodology for Edge AI,...
Edge AI and Vision Alliance
 
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
“Addressing Evolving AI Model Challenges Through Memory and Storage,” a Prese...
Edge AI and Vision Alliance
 
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Viral>Wondershare Filmora 14.5.18.12900 Crack Free Download
Puppy jhon
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
Artificial Intelligence in the Nonprofit Boardroom.pdf
Artificial Intelligence in the Nonprofit Boardroom.pdf
OnBoard
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc Webinar - 2025 Global Privacy Survey
TrustArc
 
Your startup on AWS - How to architect and maintain a Lean and Mean account
Your startup on AWS - How to architect and maintain a Lean and Mean account
angelo60207
 
Data Validation and System Interoperability
Data Validation and System Interoperability
Safe Software
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
Mastering AI Workflows with FME - Peak of Data & AI 2025
Mastering AI Workflows with FME - Peak of Data & AI 2025
Safe Software
 
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
FME for Distribution & Transmission Integrity Management Program (DIMP & TIMP)
Safe Software
 
Bridging the divide: A conversation on tariffs today in the book industry - T...
Bridging the divide: A conversation on tariffs today in the book industry - T...
BookNet Canada
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Reducing Conflicts and Increasing Safety Along the Cycling Networks of East-F...
Safe Software
 

Angularjs - lazy loading techniques

  • 2. Introduction Nir Kaufman [email protected] AngularJS infrastructures - lazy loading techniques: 1. Introducing the lazy loading challenges with AngularJS 2. Review a working demo project [email protected]
  • 3. overview AngularJS encourage us to break our code into smaller pieces. Modules services directives controllers filters constants [email protected]
  • 4. overview Separating your code into multiple files considered a best practice when building large apps with angular. Angular seed project: ❖ js/ angular.module('myApp.controllers', []). ■ ■ ■ ■ ❖ controllers.js services.js directives.js filters.js partials/ ■ partial1.html ■ partial2.html controller('MyCtrl1', function() { }) .controller('MyCtrl2', function() { }); [email protected]
  • 5. overview We can define our modules as dependencies: angular.module('myApp',['ngRoute', 'myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers', ’ngRoute’, ’ngResource’, ’ui.bootstrap’, ]). [email protected]
  • 6. overview but we must load all of our resources ahead: <script src="lib/angular.js"></script> <script src="lib/angular-route.js"></script> <script src="js/app.js"></script> <script src="js/services.js"></script> <script src="js/controllers.js"></script> <script src="js/filters.js"></script> <script src="js/directives.js"></script> ……………….. <script src="lib/angular-resource.js"></script> <script src="lib/angular-bootstrap.js"></script> <script src="lib/underscore.js"></script> [email protected]
  • 7. overview All components must register against our module on bootstrap. otherwise we can't use them. Error: Argument ‘myController’ is not a function, got undefined register Lazy Loading Angular components [email protected]
  • 8. solution We need to answer those 3 questions in order to solve this challenge: ● How to lazy load scripts async ? ● How to register our components against our module after bootstrap? ● When & where the actual loading occurs? [email protected]
  • 9. loading RequireJS provides a clean way to load and manage dependencies for our applications. <script data-main="main" src="require.js"></script> define(function () { // module code }) require([‘module’], function (module) { // use this module }) http://requirejs.org/ [email protected]
  • 10. register Components register against the module in the config phase using providers. For instance, we can register our controller manually using the ‘$controllerProvider’: angular.module('moduleName', []) .config(function($controllerProvider) { $controllerProvider.register('Ctrl', function () { // controller code }) }); [email protected]
  • 11. register All components can be registered with their matching provider methods: // services can register with $provide $provide.service() $provide.factory(), $provide.value(), $provide.constant(), // other components use specific providers $controllerProvider.resgister() $animateProvider.resgister() $filterProvider.resgister() $compileProvider.directive() [email protected]
  • 12. register we need to hold a reference to this provider in order to use it later in our code: var app = angular.module('moduleName', []) .config(function($controllerProvider) { app.loadController = $controllerProvider.register; }) }); app.loadController(‘someCtrl’, function ($scope) {}) [email protected]
  • 13. when to load Where in the application should the actual loading take place? ● when routing to a view - $routeProvider ● when loading content - <ng-include> ● in response to event - like click or hover [email protected]
  • 14. routing The route object contain a ‘resolve’ property that can accept a map of promises and wait for them to resolve before performing the route angular.module('moduleName', []) .config(function($routeProvider) { $routeProvider.when('/', { templateUrl: 'view.html', controller : 'controller.js', resolve : // promise }) }) }); [email protected]
  • 15. routing If every view managed by a controller we can reflect that in our project structure by packing them together & come up with naming conventions: ❖ views ➢ view-name ■ view-name.html ■ view-name.js .controller(‘viewNameCtrl’, …. ➢ another-view ■ another-view-name.html ■ another-view-name.js [email protected]
  • 16. events We can load our dependencies as a reaction to an event. we can be creative and load our resources depending on the user behaviour: ● load only when a user start to fill a form ● load by mouse position ● load when a response comming back from the server [email protected]
  • 17. modules What about module loading? ocLazyLoad is probably the best solution for lazy loading angular modules (for now): ● Dependencies are automatically loaded ● Debugger like (no eval code) ● The ability to mix normal boot and load on demand ● Load via the service or the directive ● Use your own async loader (requireJS, script.js ...) https://github.com/ocombe/ocLazyLoad [email protected]
  • 18. summary Lazy loading in Angular can be achived today with minimum effort. to keep our loading infrastructure flexible: 1. keep the loading logic in separated services this will make our life easier when this feature will be officially supported 2. use naming conventions this way developers can integrate more easily when moving between projects [email protected]
  • 19. summary Thank You! Demo project source code: https://github.com/nirkaufman/lazyLoadingDemo [email protected]