How do add attributes to window in Ember

#1

I am using a plugin Dayjs, and want to be available like MomentJs in window scope – window.moment. I am manually adding it to window from a utils file.

//.../utils/dayjs.js
import dayjs from 'dayjs'
...
window.dayjs = dayjs;
...

Is there any better way to do the same from ember perspective ?

#2

and I also at some point in one of component.js files, appending script tag to the document.head. Considering the script content is from the same domain and secure.

//.../someComponent/component.js
...
appendScript() {
      var script = document.createElement('script');
      script.type = 'text/javascript';
      script.text = locale.content;
      script.text += `dayjs.locale('${locale}')`;
      document.head.appendChild(script);
}

Is there any other approach to accomplish this too ?

-TIA

For #1, I think what you’re doing is fine. To ensure that it runs before you need it anywhere, you can move that code into app.js, which is where your app boots from.

For #2, I don’t see a reason that code needs to be in a separate tag. You can probably call the dayjs.locale function directly.

Thanks @ef4.

#2

DayJs cant load the file unless you invoke it.

Ref: Locale Files as UMD or Browser Injectable Bundle · Issue #739 · iamkun/dayjs · GitHub

That still doesn’t need a separate script tag. They showed that way because they’re assuming nothing about your build system.

It looks like there are two steps to enabling a locale. First you need to make sure the right module is loaded, and then you call the dayjs.locale function to activate it.

If you’re using ember-auto-import and you’ve configured it to support dynamic imports, you can do it like this (probably in your application route’s beforeModel hook, so that it runs early):

await import(`dayjs/locale/${myLocale}`);
dayjs.locale(myLocale);
1 Like