WordPress: Preload next post images

This is what cam of the other piece of code – BIG thank you to @Ivan Ivanic

<?php
    $next_post = get_adjacent_post(false, '', false );// set last param to true if you want post that is chronologically previous
    //for debug
    if(!empty($next_post)){
       echo 'Next post title is: '.$next_post->post_title;
    } else {
        echo 'global $post is not set or no corresponding post exists';
    }
    $args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_parent' => $next_post->ID);
    $attachments = get_posts($args);
    // print attachments for debug
    echo '<pre>';print_r($attachments);echo '</pre>'; ?> <script type="text/javascript">
    $(document).ready(function(){
        var images="";
        <?php foreach($attachments as $attachment):
            $mime = $attachment->post_mime_type;
            if($mime == 'image/jpeg' || $mime == 'image/gif' || $mime == 'image/png'): 
        ?>
        images += '<img src="https://wordpress.stackexchange.com/questions/12913/<?php echo $attachment->guid ?>" style="display:none" />';
        <? endif; endforeach; ?>
        if(images != ''){
            $('body').append(images);
        }
    }); </script>