13

I want to create a fallback if moment js is not loaded from CDN. I couldn't find any helpful resource online, neither on momentjs.com to detect if Moment js is present.

Here's my code :

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.min.js"></script>
<script>
    // If moment.js is not loaded, use the fallback
    if () { 
        document.write('<script src="assets/plugins/moment/moment.min.js"><\/script>');
    }
</script>
Garric
  • 552
  • 3
  • 13
  • 29

2 Answers2

17

Moment attaches itself to the window when it loads, so you could do:

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>
<script>
    if (!window.moment) { 
        document.write('<script src="assets/plugins/moment/moment.min.js"><\/script>');
    }
</script>
iamalismith
  • 1,531
  • 9
  • 22
1

I prefer writing the one-liner found this answer

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>
<script>window.moment || document.write('\x3Cscript src="assets/plugins/moment/moment.min.js" type="text/javascript">\x3C/script>')</script>
Abdul Hameed
  • 1,025
  • 12
  • 27