Mi aplicación angular 2 tarda mucho tiempo en cargarse para los usuarios primerizos, necesito ayuda para acelerarla


A continuación he pegado en mi aplicación.archivo ts.

Estoy usando angular2, con firebase y typescript.

¿Es la razón por la que es lento porque tengo muchas rutas y estoy inyectando muchos archivos?

Además, mi aplicación funciona bien es solo para los usuarios que visitan por primera vez la página de inicio Tengo este problema para.

No estoy seguro de si el bootstrap se puede mejorar en la parte inferior o si estoy haciendo algo mal.

Esta es mi aplicación.archivo ts:

import {Component, bind, provide, Injectable} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser'
import {NgIf} from 'angular2/common';
import {Router, Location, ROUTER_BINDINGS, RouterOutlet, RouteConfig, RouterLink, ROUTER_PROVIDERS, APP_BASE_HREF, CanActivate, OnActivate,
    ComponentInstruction} from 'angular2/router';
import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http';
import {ANGULAR2_GOOGLE_MAPS_PROVIDERS} from 'angular2-google-maps/core';
import {enableProdMode} from 'angular2/core';
enableProdMode();

import {LoggedInRouterOutlet} from './interceptor';

import {AuthService} from './services/authService/authService';
import {SocialService} from './services/socialService/socialService';
import {UserService} from './services/userService/userService';
import {OrganisationService} from './services/organisationService/organisationService';
import {NotificationService} from './services/notificationService/notificationService';
import {EmailService} from './services/emailService/emailService';

import {UserProfile} from './models/profile/profile';
import {Organisation} from './models/organisation/organisation';

import {HeaderNavigation} from './components/header/header';
import {HeaderNavigationLoggedIn} from './components/header/headerNavigationLoggedIn';
import {HeaderNavigationLoggedInCompany} from './components/header/headerNavigationLoggedInCompany';
import {Footer} from './components/footer/footer';
import {SideMenuCompany} from './components/header/sideMenuCompany';
import {SideMenuUser} from './components/header/sideMenuUser';
import {Splash} from './components/splash/splash';

import {CreateJob} from './components/createJob/createJob';
import {SearchJobs} from './components/searchJobs/searchJobs';
import {Login} from './components/login/login';
import {Applications} from './components/applications/applications';
import {Register} from './components/register/register';
import {ForgotPassword} from './components/forgotpassword/forgotpassword';
import {ChangePassword} from './components/changepassword/changepassword';
import {ChangeEmail} from './components/changeemail/changeemail';
import {SocialRegister} from './components/socialregister/socialregister';
import {Admin} from './components/admin/admin';
import {Contact} from './components/contact/contact';
import {SearchUsers} from './components/searchusers/searchusers';

import {Jobs} from './components/job/jobs';
import {CompanyProfile} from './components/company/company';
import {Home} from './components/home/home';
import {Dashboard} from './components/dashboard/dashboard';
import {Profile} from './components/profile/profile';
import {UserApplications} from './components/userApplications/userApplications';

@Component({
    selector: 'app',
    providers: [UserService, UserProfile, OrganisationService, Organisation],
    template: `

        <Splash *ngIf="isLoggedIn"></Splash>    

        <HeaderNavigation *ngIf="!isLoggedIn"></HeaderNavigation>       

        <HeaderNavigationLoggedIn *ngIf="isLoggedIn && isUserLogin"></HeaderNavigationLoggedIn>
        <HeaderNavigationLoggedInCompany *ngIf="isLoggedIn && isCompanyLogin"></HeaderNavigationLoggedInCompany>

        <SideMenuCompany *ngIf="isLoggedIn && isCompanyLogin"></SideMenuCompany>
        <SideMenuUser *ngIf="isLoggedIn && isUserLogin"></SideMenuUser>

        <div class="content">
            <router-outlet></router-outlet> 
        </div>     
    `,
    directives: [RouterOutlet, RouterLink, Splash, HeaderNavigation, HeaderNavigationLoggedIn, NgIf, HeaderNavigationLoggedInCompany, SideMenuCompany, SideMenuUser, Footer, LoggedInRouterOutlet]
})

@RouteConfig([
    { path: '/', component: Home, as: 'Home', data:{title: 'Welcome Home'}},
    { path: '/home', component: Home, as: 'Home', useAsDefault: true},
    { path: '/login', component: Login, as: 'Login' },  
    { path: '/register/:id', component: Register, as: 'Register' },
    { path: '/forgotpassword', component: ForgotPassword, as: 'ForgotPassword' },
    { path: '/dashboard', component: Dashboard, as: 'Dashboard' },
    { path: '/search', component: SearchJobs, as: 'Search' },   
    { path: '/profile', component: Profile, as: 'Profile' },
    { path: '/settings', component: CompanyProfile, as: 'Settings' },
    { path: '/jobs', component: Jobs, as: 'Jobs' },
    { path: '/password', component: ChangePassword, as: 'Password' },
    { path: '/email', component: ChangeEmail, as: 'Email' },
    { path: '/applications', component: Applications, as: 'Applications' },
    { path: '/socialRegister/:id', component: SocialRegister, as: 'SocialRegister' },
    { path: '/socialRegister', component: SocialRegister, as: 'SocialRegister' },
    { path: '/applys', component: UserApplications, as: 'Applys' },
    { path: '/contact', component: Contact, as: 'Contact' },
    { path: '/searchTeachers', component: SearchUsers, as: 'SearchUsers' },
    { path: '/createJob', component: CreateJob, as: 'CreateJob' },
    { path: '/adminmarkchris2016', component: Admin, as: 'AdminMarkChris2016' },

    { path:'/**', redirectTo: ['Home']}
])

@Injectable()

export class AppComponent {
    router: Router;
    location: Location;
    authService: AuthService;
    userService: UserService
    isLoggedIn: boolean = false;
    isCompanyLogin: boolean = false;
    isUserLogin: boolean = false;
    userProfile: UserProfile;   

    constructor(_router: Router, _location: Location, _authService: AuthService, _userService: UserService, _userProfile: UserProfile){ 
        this.router = _router;
        this.location = _location;
        this.authService = _authService;
        this.userService = _userService;
        this.userProfile = _userProfile;

        this.isUserLoggedIn(this.location.path());

        //On refresh
        this.router.subscribe((currentRoute) => {
            this.isUserLoggedIn(currentRoute);
        })  
    }

    isUserLoggedIn(currentRoute): void{ 
        this.authService.checkIfLoggedIn().then((response) => { 
            this.isLoggedIn = response

            if(this.isLoggedIn){
                this.isUserOrganisationOrTeacher();                 
            }   

            if(currentRoute.substring(0, 14) == "socialRegister" || currentRoute == "socialRegister" || currentRoute == "home" || currentRoute == "contact" || currentRoute == "" || currentRoute == "forgotpassword" || currentRoute == "login" || currentRoute.substring(0, 8) == "register"){
                this.isCompanyLogin = false;
                this.isUserLogin = false;
                this.isLoggedIn = false;
            }           
        });  
    }

    isUserOrganisationOrTeacher(): void{
        this.userService.checkIfProfileExists().then((response) => {
            this.isCompanyLogin = false;
            this.isUserLogin = false;       

            if(response){
                this.isUserLogin = true;
                this.isCompanyLogin = false;
            }else{
                this.isCompanyLogin = true; 
                this.isUserLogin = false;                   
            }
        }); 
    }       
}

bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'}), HTTP_PROVIDERS, AuthService, SocialService, UserService, EmailService, OrganisationService, NotificationService, ANGULAR2_GOOGLE_MAPS_PROVIDERS]);
Author: SnareChops, 2016-02-07

5 answers

Para tener algo listo para la producción (y acelerarlo), debe empaquetarlo.

Me refiero a transpilar todos los archivos en JavaScript y concatarlos de la misma manera que Angular2 lo hace, por ejemplo. De esta manera tendrá varios módulos contenidos en un solo archivo JS. De esta manera, reducirá el número de llamadas HTTP para cargar el código de su aplicación en el navegador.

De hecho, para la siguiente configuración de SystemJS, tendrá una llamada por módulo (es adecuado para el desarrollo, pero no realmente eficiente en la producción):

<script>
  System.config({
    packages: {        
      app: {
        format: 'register',
        defaultExtension: 'js'
      }
    }
  });
  System.import('app/boot')
        .then(null, console.error.bind(console));
</script>

Esta respuesta podría dar pistas sobre cómo funciona la resolución del módulo:

Puedes hacer este empaquetado usando Gulp y sus plugins:

Ver las siguientes respuestas:

 15
Author: Thierry Templier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:27

Me encontré con este mismo problema, básicamente solo necesita ejecutar la compilación de webpack en modo de producción.

Para hacer esto instale webpack globaly npm install webpack -g Una vez instalado, ejecute webpack -p desde su directorio raíz de aplicaciones. Esto redujo el tamaño de mi archivo de más de 5MB a unos 700KB

 6
Author: David Herod,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-12 00:51:30

Su problema está probablemente relacionado con el tamaño del archivo entregado al cliente. 6.9 MB es enorme tanto en términos de red como de tiempo de análisis/evaluación.

Sugerencias:

  1. Reduce tu solicitud
  2. Divídalo en varios paquetes (vendedores.js, core.js, ...)
 4
Author: Oleg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-07 13:20:49

Aunque tarde, para la gente que viene aquí ahora...si está utilizando angular2+, intente

ng build --prod --env=<staging or prod or your env file>

Hará AoT, agrupando cache busting y minification todo en un solo comando. Más deatils se pueden encontrar en el sitio web oficial de Angular en ng build sección . En mi caso uno de los chunk era en realidad 2.4 MB que se redujo a 450 + KB, pero después de incluir --prod se redujo aún más a 200+KB

El buen tamaño para una aplicación depende. Angular2 tiene el concepto de carga lenta de código o chunking. Puede dividir su aplicación en trozos (como la interfaz de usuario y la interfaz de usuario) y cargarlos bajo demanda para que no sea necesario cargar inicialmente toda la aplicación, lo que ayudará a reducir el tiempo de carga. Los siguientes artículos podrían ser de extra ayuda:

 4
Author: Nidhin David,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-28 17:08:28

Otro posible enfoque para acelerar su aplicación es usar Carga lenta

De esa manera, tu AppModule reducirá las importaciones y los módulos serán llamados bajo demanda.

 0
Author: Georgios,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-04 14:16:24