Load external js file with crossorigin check in WordPress
Let’s say we want to load jQuery. Not the one WordPress gives us, but a version we tested on and know for sure everything is going to work.
As normal, we deregister (in functions.php) WordPress jQuery, register our own and enqueue the script.
wp_deregister_script( 'jquery' ); // deregisters the default WordPress jQuery wp_register_script('jquery', 'https://code.jquery.com/jquery-1.12.4.min.js'); // register the external file wp_enqueue_script('jquery'); // enqueue the external file
Ok, now we are getting CORS errors like:Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at
Taking a look at https://code.jquery.com/, we find the following code
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
Taking the integrity and crossorigin from there, we just need to add this line of code
wp_script_add_data( 'jquery', array( 'integrity', 'crossorigin' ) , array( 'sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=', 'anonymous' ) ); // add data to the script