×
FalconChen
2020-05-13 01:47
#daily tips# iis7 服務器開啓gzip動態內容壓縮有問題,只能使用php壓縮,對wp_send_json進行了封裝,實現了wp_send_json的gzip壓縮,原來2.8M的內容壓縮只要110k。效果驚人,用戶代理不支持時fallback回原來的wp_send_json。
php 代码片断
<?php

function wp_send_json_gzip( $response, $status_code = null ) {

            if(!isset($_SERVER['HTTP_ACCEPT_ENCODING']) 
            || strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') === false
            || !function_exists('gzencode')){ 
                //如果瀏覽器不支持gzip壓縮或者沒有gzencode函數,fallback
                return wp_send_json($response, $status_code);
            }

            @header( 'Content-Type: application/json; charset=' . get_option( 'blog_charset' ) );
            if ( null !== $status_code ) {
                status_header( $status_code );
            }
            
            header('Content-Encoding: gzip');
            header('X-By-Falcon: gzip on the fly', false);
            ob_start();
            echo wp_json_encode( $response );
            $buffer = ob_get_contents();     
            ob_end_clean();       
            echo gzencode($buffer, 9);

            if ( wp_doing_ajax() ) {
                wp_die(
                    '',
                    '',
                    array(
                        'response' => null,
                    )
                );
            } else {
                die;
            }
        }
0

暂无评论