Load external JavaScript files from Angular
This project shows an example of executing an external JavaScript file from an Angular component. It can also work if you invoke a URL.
Why is this useful? The default option is to include the script in index.html. The problem is that it will run whether you need it or not. With this solution the script is only loaded in the components that actually require it, reducing response time and improving SEO.
You can review the repository https://github.com/al118345/Angular_con_javascript where the example used in this page is stored. You can also watch the following video example https://www.youtube.com/watch?v=yO-_SE5gUfQ:Implementation
The first step is to create a new service responsible for loading the desired JavaScript. If you create it as a service, you can reuse it in multiple components. In our example, that service loads the JavaScript required to add YouTube videos to the view. Once created, add the following code: This is the important part. Its role is to append the selected script into the head tag with the parameters we specify. In the src field you define the path, which can be a URL or a local JavaScript file. We load it asynchronously to improve response time and finally append it into the desired HTML area, in this case the head. Finally, wherever you need it, invoke the service so the script is loaded at the precise moment shown below. When does this pattern make sense?
Use this approach when a script is only needed by one page or one feature: maps, video widgets, payment providers, analytics helpers, editors or visualizations. Loading it globally in index.html makes every visitor pay that cost, even if most users never open that feature.
If the script is essential for the whole application, index.html is still acceptable. The key decision is whether the dependency belongs to the entire site or only to a specific route.
Important detail with SSR
In Angular Universal or SSR, document and window do not exist on the server. The safest implementation checks the platform before touching the DOM and avoids executing browser-only code during server rendering.
Avoid loading the same script twice
Before appending a script, check whether it already exists. This prevents duplicate listeners, repeated widgets and hard-to-debug behavior when the user navigates between routes.
Practical checklist
- Load the script only on the component that needs it.
- Use async or defer when possible.
- Check SSR before using document or window.
- Reuse the existing script if it is already loaded.
- Prefer an official npm package when the provider maintains one.