The easiest way to add external dependencies to your Angular project is npm.. The workaround is to add a script tag to the web page that hosts your application. However, this option only works if you have access to the host page. Other than that, you need to load the JavaScript file dynamically. This is actually pretty easy to do in JavaScript. Angular needs to take advantage of some of the built-in objects to do that. In this tutorial, you will learn some strategies for attaching external JS files using custom services.
Add a script using Strategy 1: src attribute
Many JavaScript libraries are available via a content delivery network (CDN). These are optimized to serve the JS library very quickly.There are several large CDNs that host multiple JS libraries (Google’s CDN and cdnjs); Other libraries have their own CDN. In this tutorial, we will load the Google API client library for browser JavaScript.This is another name GAPI.. This is a set of client libraries for calling Google APIs in various languages such as Python, Java and Node. It is used by thousands of internal and external web pages for easy connection with Google Login, Google Drive, and Google APIs.
Our service will add Screenplay Tag the document body, src Attribute of “https://apis.google.com/js/”
ScriptService
To achieve that goal, ScriptService needs two things.
- Reference to document body
- How to create an element
You can access the component elements using the following decorators ViewChild, ViewChildrenHowever, you can insert a Document object via the constructor to reference the document itself.This will allow you to add scripts to document.body..
Angular provides Renderer2 classes for implementing custom rendering. So it contains everything you need to work with DOM elements. appendChild () Method.Pass directly loadJsScript () From the calling component.
The full service code is:
import { Renderer2, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/common'; export class ScriptService { constructor( @Inject(DOCUMENT) private document: Document ) { } /** * Append the JS tag to the Document Body. * @param renderer The Angular Renderer * @param src The path to the script * @returns the script element */ public loadJsScript(renderer: Renderer2, src: string): HTMLScriptElement { const script = renderer.createElement('script'); script.type="text/javascript"; script.src = src; renderer.appendChild(this. document.body, script); return script; } }
Call the loadJsScript () method in Angular and JavaScript
In AppComponentCalled loadJsScript () Use the method to use the new script. Both Renderer2 and ScriptService are inserted as constructor arguments. next, ngOnInit,Call loadJsScript ()..Returns the script element as HTMLScriptElement.. This gives you access to a number of properties and methods that make scripting much easier to work with.For example, you can bind a method to On-road When onerror event.
One pitfall that often frustrates developers unfamiliar with loading dynamic scripts in Angular is the global script object (in TypeScript). $ Because I don’t know what it is (in jQuery).Cannot be defined using const Also Let me, Because it needs to be prefixed this., It does not reference global variables, but it does refer to variables defined at the component level. instead, declare And give it a type Any, NS declare let gapi: any;
..
This is perfect AppComponent code:
import { Component, OnInit, Renderer2 } from "@angular/core"; import { ScriptService } from "./services/script.service"; const SCRIPT_PATH = 'https://apis.google.com/js/api.js'; declare let gapi: any; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.css"] }) export class AppComponent implements OnInit { constructor( private renderer: Renderer2, private scriptService: ScriptService ) { } ngOnInit() { const scriptElement = this.scriptService. loadJsScript(this.renderer, SCRIPT_PATH); scriptElement.onload = () => { console.log('Google API Script loaded'); console.log(gapi); // Load the JavaScript client library. // (the init() method has been omitted for brevity) gapi.load('client', this.init); } scriptElement.onerror = () => { console.log('Could not load the Google API Script!'); } } }
Strategy 2: Add a data block script using Sentence attribute
In some cases, the script element is used as a data block containing JSON-LD (type = ”application / ld + json”). JSON-LD is a Resource Description Framework (RDF) serialization that allows you to publish linked (or structured) data using JSON. This structured data is available to all interested consumers. Here is a sample script:
<script type="application/ld+json"> { "@context": "http://schema.org", "@type": "WebSite", "url": "http://website.com", "name": "wbs", "description": "Web Studio" } </script>
The service code for adding JSON-LD scripts is not much different from JavaScript.Set the script text in the result in addition to the different types JSON.stringify () Method. Converts a JSON object to a JSON string.
public setJsonLd(renderer: Renderer2, data: any): void { let script = renderer.createElement('script'); script.type="application/ld+json"; script.text = `${JSON.stringify(data)}`; renderer.appendChild(this. document.body, script); }
Please note setJsonLd () Method does not return HTMLScriptElement, Because the content of the script is local and will be available as soon as it is added to the document.
const JSON_LD_DATA = ` { "@context": "http://schema.org", "@type": "WebSite", "url": "http://website.com", "name": "wbs", "description": "Web Studio" } `; ngOnInit() { this.scriptService.setJsonLd(this.renderer, JSON_LD_DATA); console.log('JSON_LD_DATA Script loaded'); }
A complete demo of this tutorial codesandbox.io..
Read: How to Optimize Angular Applications
Conclusion
In this tutorial, you learned some strategies for attaching external JS files using Angular’s built-in objects.Nevertheless npm This is the preferred method for importing external libraries into your project, but the techniques presented here today provide a good alternative.
"load" - Google News
August 22, 2021 at 07:46PM
https://ift.tt/3ke8cvG
How to dynamically load an external script in Angular - Illinoisnewstoday.com
"load" - Google News
https://ift.tt/2SURvcJ
https://ift.tt/3bWWEYd
Bagikan Berita Ini
0 Response to "How to dynamically load an external script in Angular - Illinoisnewstoday.com"
Post a Comment