The nightmare of loading external js files to your angular project

nour karoui
2 min readFeb 22, 2021

--

You’re building an angular project. In order to not waste time, you bought a ready made template and decided to integrate it.

Now here’s the hard part, you have some JS files you need to integrate to the angular project. You load them , but when switching pages using routerLink, nothing seems to work properly.

I guess we’ve all been in such a situation, well at least, I know I have. So here are some tips and tricks that helped me solve this problem.

So, let’s assume that in your project you have two pages, home page and product page.

project architecture

1- In your home page, you have a slider and carousel, that both need the js files. (slider component and carousel home component)

home.component.html

2- In the product page, you have a carousel that needs the js files. (carousel product component)

product.component.html

So, here’s how you do it

1- Creating a service

Create a service: ExternalFilesService and put the JS files paths and loading scripts function.

2- Loading scripts in the right place

Now, you should make sure you call loadScripts function only once per page, in other words you’d call it in the:

carousel product component AND slider component

OR

carousel product component AND carousel home component.

3- Loading scripts in the right time

Last and most importantly, loading the JS files should be LAST.

For example, if we’re fetching data from the backend we should call loadScripts after fetching data.

So, for this example, let’s assume, in the home page we’re fetching some data in the carousel component.

So we should load scripts in the home carousel component and not in the slider.

here’s the final implementation:

That’s all folks

This method worked well for me, I’m sure there are areas of improvements and optimisation. Let me know in the comments if you have other methods.

--

--