1

I'm using bootstrap 4.4.1 (the latest) and am using stackpath.bootstrapcdn.com. It appears that loading my webpages is slow.

Does anyone else encounter it?

Should I just download the css and refer to it locally?

  • I never had problems with the stackpath cdn. Maybe try another one like jsdelivr or maxcdn. – Timo Mar 15 '22 at 19:11

1 Answers1

1

You can do both. If you have trouble with a CDN or for some other reason need a fallback, you can test if the CSS is loaded for example this way:

<script>
setTimeout(function() {
  let loaded = false
  for (let s in document.styleSheets)  {
    if (document.styleSheets[s].href && 
       document.styleSheets[s].href.indexOf('bootstrap.min.css')) loaded = true
  }
  if (!loaded) {
    let link = document.createElement('link')
    link.href = 'path/to/fallback/bootstrap.min.css'
    link.rel = 'stylesheet'
    document.head.appendChild(link)
}
}, 500)
</script>

If bootstrap.min.css is not loaded after 500ms a new <link href="...> pointing to a local file will be inserted to the <head> section of the document..

There is imho two major reasons for using a CDN

  1. If you have users worldwide they will (probably) experience faster load times
  2. You avoid a lot of hits / load on your own server

There is imho two reasons for not using a CDN

  1. You really dont know for sure if a ressource is available, and you dont even know if a certain CDN exists tomorrow at all
  2. Theoretically you can use a CDN to track users. and some CDN's does that.
Timo
  • 2,922
  • 3
  • 29
  • 28
davidkonrad
  • 83,997
  • 17
  • 205
  • 265
  • 1
    Two minor things, a) remove the tilde `~` and use [document.head](https://developer.mozilla.org/en-US/docs/Web/API/Document/head) - and maybe remove the `link.type` and let the browser guess the type. – Timo Mar 15 '22 at 19:10
  • 1
    @Timo, you are more than welcome to edit / correct the answer. Or produce a better answer based on the above. I am pensioned now, and none of my hobby projects are using CDN's because of the security risks and privacy issues. – davidkonrad Mar 15 '22 at 20:41
  • I like your answer with the timeout function and your explanation, mine ist just a beautifier, not worth an answer. Your creativity here is plus one.. – Timo Mar 16 '22 at 15:52
  • 1
    @Timo, you have improved the answer, and by that perhaps helped a lot of people in the future. This is the good spirit of SO. – davidkonrad Mar 16 '22 at 16:11