You are using onAfterRender event which is not suitable for modifying the document object because this event is triggered after the page has already been rendered. Use onAfterDispatch, onBeforeRender or onBeforeCompileHead instead.
$document->addScriptDeclaration() method is working, no problem with that.
window.event is deprecated:
instead of that you should use document.addEventListener() or window.addEventListener() on the event of DOMContentLoaded