I think you can use the PluginAPI onPageChange
function to do what you are looking for. See: Using the PluginAPI in Site Customizations
Here’s an example function:
<script type="text/discourse-plugin" version="0.8">
api.onPageChange(() =>{
randBackground();
});
function randBackground() {
$('body').css('background-color', '#'+(Math.random()*0xFFFFFF<<0).toString(16));
}
</script>
Update: If you are looking to apply similar changes to post bodies, see post #26 below.