Image loading function not working on archive.php template

archive.php doesn’t have a featured image, so this clause will short circuit your logic immediately:

if ( post_password_required() || is_attachment() || ! has_post_thumbnail() ) {
    return;
}

Try moving the has_post_thumbnail check and your $url assignment inside the clauses where they make more sense – the clauses that check for post and page.