wp_maybe_inline_styles

函数
wp_maybe_inline_styles ( No parameters )

wp_maybe_inline_styles: 这个函数用于将文件中的CSS样式内联到网页中。它检查文件是否包含任何样式,然后将它们内联到网页上。

允许小的样式被内联。

这提高了性能和可持续性,并且可以选择加入。样式表可以通过使用`wp_style_add_data`添加`path`数据,并定义文件的绝对路径来选择加入。

wp_style_add_data( $style_handle, ‘path’, $file_path ) 。

function wp_maybe_inline_styles() {
	global $wp_styles;

	$total_inline_limit = 20000;
	/**
	 * The maximum size of inlined styles in bytes.
	 *
	 * @since 5.8.0
	 *
	 * @param int $total_inline_limit The file-size threshold, in bytes. Default 20000.
	 */
	$total_inline_limit = apply_filters( 'styles_inline_size_limit', $total_inline_limit );

	$styles = array();

	// Build an array of styles that have a path defined.
	foreach ( $wp_styles->queue as $handle ) {
		if ( wp_styles()->get_data( $handle, 'path' ) && file_exists( $wp_styles->registered[ $handle ]->extra['path'] ) ) {
			$styles[] = array(
				'handle' => $handle,
				'src'    => $wp_styles->registered[ $handle ]->src,
				'path'   => $wp_styles->registered[ $handle ]->extra['path'],
				'size'   => filesize( $wp_styles->registered[ $handle ]->extra['path'] ),
			);
		}
	}

	if ( ! empty( $styles ) ) {
		// Reorder styles array based on size.
		usort(
			$styles,
			static function( $a, $b ) {
				return ( $a['size'] <= $b['size'] ) ? -1 : 1;
			}
		);

		/*
		 * The total inlined size.
		 *
		 * On each iteration of the loop, if a style gets added inline the value of this var increases
		 * to reflect the total size of inlined styles.
		 */
		$total_inline_size = 0;

		// Loop styles.
		foreach ( $styles as $style ) {

			// Size check. Since styles are ordered by size, we can break the loop.
			if ( $total_inline_size + $style['size'] > $total_inline_limit ) {
				break;
			}

			// Get the styles if we don't already have them.
			$style['css'] = file_get_contents( $style['path'] );

			// Check if the style contains relative URLs that need to be modified.
			// URLs relative to the stylesheet's path should be converted to relative to the site's root.
			$style['css'] = _wp_normalize_relative_css_links( $style['css'], $style['src'] );

			// Set `src` to `false` and add styles inline.
			$wp_styles->registered[ $style['handle'] ]->src = false;
			if ( empty( $wp_styles->registered[ $style['handle'] ]->extra['after'] ) ) {
				$wp_styles->registered[ $style['handle'] ]->extra['after'] = array();
			}
			array_unshift( $wp_styles->registered[ $style['handle'] ]->extra['after'], $style['css'] );

			// Add the styles size to the $total_inline_size var.
			$total_inline_size += (int) $style['size'];
		}
	}
}

常见问题

FAQs
查看更多 >