This works
<body onload="document.body.classList.add('loaded'); document.body.removeAttribute('onload')">
and it's not a problem for this particular case, but I need the same fuctionality on multiple elements and I hope there's a solution without giving all of them an id
attribute.
I tried
<body onload="this.classList.add('loaded'); this.removeAttribute('onload')">
and
<body onload="self.classList.add('loaded'); self.removeAttribute('onload')">
but (obviously to some) it doesn't work.
How do I get the element in which JavaScript is called from attributes like onload
, onclick
, etc.?
Elaborating my use-case:
All of my styles, except critical.css
are loading with a non-blocking hack like
<link rel="stylesheet" media="none" onload="if(media!='all')media='all'" href="//fonts.googleapis.com/css?family=Open+Sans:300,400,600,700%7CPT+Sans+Narrow%7CSource+Sans+Pro:200,300,400,600,700,900&subset=all&display=swap" type="text/css">
I don't like that the onload="if(media!='all')media='all'"
part is still visible in DevTools after everything is loaded properly. I also don't completely understand how to do this in a better way. It would be interesting to find out the answer to my exact question, but I would also much appreciate an answer that offers the best approach. My stack is HTML5, CSS, vanilla JavaScript, PHP 7.2. No frameworks at the moment (not counting Bootstrap).