You have to execute that code when all the library and assets more in general are loaded.
When you are working with localhost everything is loaded together (almost) and you don't see any asynchronous issue: if you don't have to wait particular assets a common trick is to write your js code at the bottom part of the page, so that all the DOM is loaded before executing it.
If you want to wait all the assets instead, just use the jquery $(document).ready(...)
to wrap your function - or it's JS complicated equivalent - or, if you need to wait also fonts to load simply window.onload = function(){...}
- you can use this also if you don't have any fonts, it's just triggered later than the previous one.