Search code examples
javascripthtmlangularcdnmasonry

Angular - Loading external script through CDN on internal navigation


I'm trying to create a masonry layout by loading in <script src="https://unpkg.com/masonry-layout@4/dist/masonry.pkgd.min.js"></script> at the top of the index page and using it on a component in my web-app. This problem probably isn't masonry-specific, the general problem is an included script in the header not loading on internal navigation.

I've chosen to initialize the masonry in the HTML. The problem occurs when using internal navigation to get to the page. If I reload the page to the correct URL the script does its thing and creates the desired layout. However, when navigating through routerlinks the scripts doesn't load, or something else is wrong making it not apply.

Here's a picture of the correct loading which occurs when refreshing the page: enter image description here

And one of the incorrect loading when navigating internally to the page: enter image description here

The HTML for the page:

<div class="grid" data-masonry='{ "itemSelector": ".grid-item", "columnWidth": 5 }'>
  <div *ngFor="let card_text of card_array" class="grid-item">
    <div class="cardTop">
      <img src="/static/images/ordercards/greenOrderIcon.svg">
      <div class="orderId">
        Order # Some number
      </div>
    </div>
    <div class="cardMain">
      {{ card_text }}
    </div>
    <div class="cardBot">
      <a routerLink="/orders"> Learn More ></a>
    </div>
  </div>
</div>

and in the index.html the script mentioned at the top is included.

Any ideas on how to load the script each time the page is internally navigated to?


Solution

  • It's possible your angular script is running before the mansory js is loaded. Try loading the library with load-script or load-js scripts which will give you a promise of when it's finished loading, then you execute your mansory layout constructor.