compression_test()
概述
compression_test() 函数用于测试从 PHP 压缩 JavaScript 的支持情况,并基于测试结果设置一个选项。该函数仅对管理员用户有效。
关键要点
- 函数输出 JavaScript 代码来测试 PHP 压缩功能是否正常工作。
- 测试结果存储在 'can_compress_scripts' 选项中,如需重新测试需先删除此选项。
- 仅当当前用户是管理员时函数才生效,非管理员用户无影响。
- 该函数自 WordPress 2.8.0 版本引入。
Tests support for compressing JavaScript from PHP.
Description
Outputs JavaScript that tests if compression from PHP works as expected and sets an option with the result. Has no effect when the current user is not an administrator. To run the test again the option ‘can_compress_scripts’ has to be deleted.
Source
function compression_test() {
?>
<script type="text/javascript">
var compressionNonce = <?php echo wp_json_encode( wp_create_nonce( 'update_can_compress_scripts' ), JSON_HEX_TAG | JSON_UNESCAPED_SLASHES ); ?>;
var testCompression = {
get : function(test) {
var x;
if ( window.XMLHttpRequest ) {
x = new XMLHttpRequest();
} else {
try{x=new ActiveXObject('Msxml2.XMLHTTP');}catch(e){try{x=new ActiveXObject('Microsoft.XMLHTTP');}catch(e){};}
}
if (x) {
x.onreadystatechange = function() {
var r, h;
if ( x.readyState == 4 ) {
r = x.responseText.substr(0, 18);
h = x.getResponseHeader('Content-Encoding');
testCompression.check(r, h, test);
}
};
x.open('GET', ajaxurl + '?action=wp-compression-test&test='+test+'&_ajax_nonce='+compressionNonce+'&'+(new Date()).getTime(), true);
x.send('');
}
},
check : function(r, h, test) {
if ( ! r && ! test )
this.get(1);
if ( 1 == test ) {
if ( h && ( h.match(/deflate/i) || h.match(/gzip/i) ) )
this.get('no');
else
this.get(2);
return;
}
if ( 2 == test ) {
if ( '"wpCompressionTest' === r )
this.get('yes');
else
this.get('no');
}
}
};
testCompression.check();
</script>
</pre><p class="wporg-dot-link-list"><a href="https://developer.wordpress.org/reference/files/wp-admin/includes/template.php/">View all references</a> <a href="https://core.trac.wordpress.org/browser/tags/6.9.4/src/wp-admin/includes/template.php#L2494">View on Trac</a> <a href="https://github.com/WordPress/wordpress-develop/blob/6.9.4/src/wp-admin/includes/template.php#L2494-L2546">View on GitHub</a></p></section>
<section class="wp-block-wporg-code-reference-related" data-nosnippet="true"><h2 id="related" class="is-toc-heading wp-block-heading has-heading-5-font-size" tabindex="-1" ><a href="#related">Related</a></h2> <section style="margin-top:var(--wp--preset--spacing--20)" class="wp-block-wporg-code-table" id="uses"><figure class="wp-block-table "><table><thead><tr><th scope="col">Uses</th><th scope="col">Description</th></tr></thead><tbody><tr class=""><td><a href="https://developer.wordpress.org/reference/functions/wp_json_encode/">wp_json_encode()</a><code>wp-includes/functions.php
Encodes a variable into JSON, with some confidence checks.
wp_create_nonce()wp-includes/pluggable.php
Creates a cryptographic token tied to a specific action, user, user session, and window of time.
Changelog
| Version | Description |
|---|---|
| 2.8.0 | Introduced. |