-
Notifications
You must be signed in to change notification settings - Fork 530
Cannot use inline 'onload' because of CSP #312
Comments
Looks good! Thanks for noting. It should work the same yes, but I'm not sure if there's a possibility of the CSS loading from cache before the onload event is bound. It does make me wonder if a timeout might be more dependable, since it's not Worth testing. Anyway, I'd love a readme edit if you'd like to. Otherwise we'll aim to get to it when we can. |
Nice find & workaround @petervtzand ! One question though, why don't you "activate" the stylesheet in the link by setting the rel-attribute to "stylesheet" rather than changing the media attribute? |
I've used this example of the filament group: https://www.filamentgroup.com/lab/load-css-simpler/. This seems to be their new and simpler approach. |
Here is a variant if you have multiple styles <script nonce>
Array.prototype.slice.call(document.querySelectorAll("[data-loadcss]")).map(function (e) {
e.addEventListener("load", function() {
this.media = "all"
});
})
</script> or shorter es6 syntax <script nonce>
[...document.querySelectorAll("[data-loadcss]")].map((e) => e.addEventListener("load", (e) => e.target.media = "all"));
</script> |
Btw, I've noticed a weird bug where event listener did not trigger in Edge 18. So I've had to add this workaround. Works with onchange though, weird. if (navigator.userAgent.match("Edge/")) {
e.media = "all";
} |
Sorry for necromancing an old issue with a (unrelated) question. Again, sorry for reviving an issue with a unrelated (noob) question. I do look forward to your reply! I've tried to implement it here: /~https://github.com/TheVoxSiren/voxsiren.net/blob/main/index.html#L7 |
When you have a CSP without
unsafe-inline
, you cannot useonload
inline. This it will throw an error, and therefore not load the css.So the following cannot be used.
So then I thought of a solution, where I use an event listener that is triggered when the css is loaded:
This seems to work, but will I get the same performance? If this does work maybe the documentation can be updated for people who don't want to add 'unsafe-inline' do their CSP?
The text was updated successfully, but these errors were encountered: