Script for svg only fires after refresh

I have two clickable svg files on this wordpress page customized with CSS and JavaScript. The first svg (size: 447kb) loads without a problem and the script fires when clicked. The second svg loads a bit longer (size: 993kb) and .onclick only works if the page is refreshed.(Console says: Uncaught TypeError: Cannot set property ‘onclick’ of null)

After a lot of research I suspect this to be an Ajax issue. There is no option to deactivate Ajax so I tried following function to put the script into the footer:

function load_js_assets() {
    if( is_page(#) ) {
        wp_register_script('script', 'url/script.js', array( 'jquery' ), '0', false);
        wp_enqueue_script('script');
    } 
}

add_action('wp_enqueue_scripts', 'load_js_assets', 99999);

This didn’t do anything.

Within the script.js I tried window.onload, window.addEventListener("load", function(){}, document.load, document.addEventListener("DOMContentLoaded",…) nothing worked.

Currently my script goes like this:

window.addEventListener("load", function(){

(function() {
/*function for svg1*/
}; 
})();

(function(){
/*function for svg2*/
};
})();

});

Do I have any other options here please? (Please excuse my non-DRY way of coding, I’m still a noob)

19 thoughts on “Script for svg only fires after refresh”

Leave a Comment