Step 1: save the code as a new js file, say main.js
Step 2: add a conditional function to function.php of your theme that would say something around the lines:
if (is_shop() || is_product_category()) {
wp_enqueue_script('main', get_template_directory_uri() . '/js/main.js', false, false, true);
}
Check this page for conditional tags based on your needs:
https://docs.woocommerce.com/document/conditional-tags/
Hope it helps!
Edit:
For inline scripting you could do (e.g. inside footer.php):
if (is_shop() || is_product_category()) {?>
<script>
jQuery(document).ready(function($){
if ( $(window).width() < 768 || window.Touch) {
$('html, body').animate({ scrollTop: $("#primary").offset().top}, 2000);
}
});
</script>
<?php}