An Angular library that helps in loading JS script on demand
npm install ng-scripterng-scripter is a simple script loader that helps in loading external JS scripts on demand.
This utility will help in decreasing the initial page load time since it gives the ability to load any JS script dynamically when required.
npm i ng-scripter
`
Yarn:
`
yarn add ng-scripter
`Setup
Import ScriptLoaderModule inside the module that requires it (AppModule or any other module)
`angular2
import { ScriptLoaderModule } from 'ng-scripter';
@NgModule({
...
imports: [
...
ScriptLoaderModule
]
})
`
Usage
Inject the ScriptLoaderService inside a component/service
`angular2
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private scriptLoaderService: ScriptLoaderService) {
} loadScript = () => {
const script: Script = {
id: 'faker-id',
src: 'https://cdnjs.cloudflare.com/ajax/libs/Faker/3.1.0/faker.min.js',
async: true,
defer: false,
crossOrigin: 'anonymous'
};
this.scriptLoaderService.loadScript(script).subscribe(
(data: Script) => console.log('Script Loaded ', data),
(err) => console.log('Script failed ', err)
);
};
}
`Options
The Script model has the following attributes.| Attribute | Required | Type | Description |
| ------------- | ------------- | ------------- | ------------- |
| id | Yes | string | An Id for the script. (Preferably Unique)
| src | Yes | string | The source url |
| async | No | boolean | Async load or not (Default : false) |
| defer | No | boolean | Defer or not (Default : false) |
| crossOrigin | No | string | CORS |
Usage of watch
`angular2
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit, OnDestroy {
private watcherSubscription: Subscription;
......
constructor(private scriptLoaderService: ScriptLoaderService) {
} ngOnInit(): void {
// get notified every time a new script is loaded the first time
this.watcherSubscription = this.scriptLoaderService.watch().subscribe(
script => {
console.log('Watcher => ', script);
}
);
}
ngOnDestroy(): void {
if (this.watcherSubscription) {
this.watcherSubscription.unsubscribe();
}
}
}
``