Developing a theme for WordPress using Bootstrap 4 I'm familiar with the suggested approach of coding a <div>
:
<div id="bootstrapCssTest" class="hidden"></div>
and checking it with JavaScript:
<script type="text/javascript">
if ($('#bootstrapCssTest').is(':visible') === true) {
$('<link href="/localcopy/css/bootstrap.css" rel="stylesheet" type="text/css" />').appendTo('head');
}
</script>
reference: "How to load local copy of bootstrap css when the cdn server is down?" but I would like a way to test the CSS without JavaScript and enqueue Bootstrap's CSS depending on if the CDN is found. Upon research I read that fopen
may not be allowed always on the server level so I opted for get_headers
, the code:
function bootstrap_css() {
$bootstrap_cdn = 'https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css';
$cdn_check = @get_headers($bootstrap_cdn);
if ($cdn_check[0] === "HTTP/1.1 200 OK") :
wp_enqueue_style('bootstrap',$bootstrap_cdn,array(),'4.2.1');
function add_cross_origin($html,$handle) {
if ('bootstrap' === $handle) {
return str_replace("media='all'","media='all' integrity='sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS' crossorigin='anonymous'",$html);
}
return $html;
}
add_filter('style_loader_tag','add_cross_origin',10,2);
else :
wp_enqueue_style('bootstrap',get_site_url() . '/css/bootstrap.min.css',false,'4.2.1');
endif;
}
add_action('wp_enqueue_scripts','bootstrap_css');
Is there a better approach to checking wether the Bootstrap CSS CDN is available that doesn't use JavaScript to test? Should I be checking anything beyond the "HTTP/1.1 200 OK"? Would cURL
be better to use then get_headers
?