我开始使用CORS来加载css跨域并使其可编辑。我在我的localhost上发现加载我的样式表(带有php扩展名)需要5秒多。它返回状态为200 OK,没有错误。正常加载<link rel="stylesheet" type="text/css" href=..."
时,它按预期工作。任何想法为什么性能的差异和该怎么办?
var css = "http://static-domain/css/a.css.php?var1=http://static-domain/img-common&var2=http://static-domain2";
loadCSSCors(css);
function loadCSSCors(stylesheet_uri) {
var _xhr = XMLHttpRequest;
var has_cred = false;
try {
has_cred = _xhr && ('withCredentials' in (new _xhr()));
} catch (e) {}
if (!has_cred) {
console.error('CORS not supported');
return;
}
var xhr = new _xhr();
xhr.open('GET', stylesheet_uri);
xhr.onload = function() {
xhr.onload = xhr.onerror = null;
if (xhr.status < 200 || xhr.status >= 300) {
console.error('style failed to load: ' + stylesheet_uri)
} else {
var style_tag = document.createElement('style');
style_tag.appendChild(document.createTextNode(xhr.responseText));
document.head.appendChild(style_tag);
}
}
xhr.onerror = function() {
xhr.onload = xhr.onerror = null;
console.error('XHR CORS CSS fail:' + stylesheet_uri);
};
xhr.send();
}
我的样式表
<?php
header('Content-Type: text/css');
$staticImgCommon = $_GET['static-img-common'];
$staticSite = $_GET['static-site-root'];
header("Access-Control-Allow-Origin: http://main-domain");
?>
*{padding:0; margin:0; border:0}
etc...