函数文档

wp_get_script_polyfill()

💡 云策文档标注

概述

wp_get_script_polyfill() 函数用于生成内联脚本,为不通过指定功能测试的浏览器添加 polyfill 脚本。它基于提供的测试条件与脚本句柄映射来构建条件性 polyfill 脚本。

关键要点

  • 函数返回一个字符串,包含条件性 polyfill 内联脚本。
  • 参数 $scripts 必须是 WP_Scripts 对象,用于访问已注册的脚本信息。
  • 参数 $tests 是一个数组,映射功能测试条件到对应的 polyfill 脚本句柄。
  • 函数会检查脚本是否已注册,处理脚本 URL 和版本号,并应用 script_loader_src 过滤器。
  • 生成的脚本使用 document.write 来同步写入 polyfill,确保在旧浏览器中正确加载。

代码示例

function wp_get_script_polyfill( $scripts, $tests ) {
	$polyfill = '';
	foreach ( $tests as $test => $handle ) {
		if ( ! array_key_exists( $handle, $scripts->registered ) ) {
			continue;
		}

		$src = $scripts->registered[$handle]->src;
		$ver = $scripts->registered[$handle]->ver;

		if ( ! preg_match( '|^(https?:)?//|', $src ) && ! ( $scripts->content_url && str_starts_with( $src, $scripts->content_url ) ) ) {
			$src = $scripts->base_url . $src;
		}

		if ( ! empty( $ver ) ) {
			$src = add_query_arg( 'ver', $ver, $src );
		}

		/** This filter is documented in wp-includes/class-wp-scripts.php */
		$src = esc_url( apply_filters( 'script_loader_src', $src, $handle ) );

		if ( ! $src ) {
			continue;
		}

		$polyfill .= (
			// Test presence of feature...
			'( ' . $test . ' ) || ' .
			/*
			 * ...appending polyfill on any failures. Cautious viewers may balk
			 * at the `document.write`. Its caveat of synchronous mid-stream
			 * blocking write is exactly the behavior we need though.
			 */
			'document.write( '<script src="' . $src . '"></script>' );'
		);
	}
	return $polyfill;
}

注意事项

  • 函数依赖于 WP_Scripts 对象来获取脚本的 src 和 ver 属性,确保脚本已正确注册。
  • 使用 document.write 可能在某些现代浏览器中引发性能问题,但在此场景下是必要的,以确保 polyfill 在旧浏览器中同步加载。
  • 脚本 URL 会通过 script_loader_src 过滤器进行修改,开发者可以利用此过滤器自定义脚本加载行为。

📄 原文内容

Returns contents of an inline script used in appending polyfill scripts for browsers which fail the provided tests. The provided array is a mapping from a condition to verify feature support to its polyfill script handle.

Parameters

$scriptsWP_Scriptsrequired
WP_Scripts object.
$testsstring[]required
Features to detect.

Return

string Conditional polyfill inline script.

Source

function wp_get_script_polyfill( $scripts, $tests ) {
	$polyfill = '';
	foreach ( $tests as $test => $handle ) {
		if ( ! array_key_exists( $handle, $scripts->registered ) ) {
			continue;
		}

		$src = $scripts->registered[ $handle ]->src;
		$ver = $scripts->registered[ $handle ]->ver;

		if ( ! preg_match( '|^(https?:)?//|', $src ) && ! ( $scripts->content_url && str_starts_with( $src, $scripts->content_url ) ) ) {
			$src = $scripts->base_url . $src;
		}

		if ( ! empty( $ver ) ) {
			$src = add_query_arg( 'ver', $ver, $src );
		}

		/** This filter is documented in wp-includes/class-wp-scripts.php */
		$src = esc_url( apply_filters( 'script_loader_src', $src, $handle ) );

		if ( ! $src ) {
			continue;
		}

		$polyfill .= (
			// Test presence of feature...
			'( ' . $test . ' ) || ' .
			/*
			 * ...appending polyfill on any failures. Cautious viewers may balk
			 * at the `document.write`. Its caveat of synchronous mid-stream
			 * blocking write is exactly the behavior we need though.
			 */
			'document.write( '<script src="' .
			$src .
			'"></scr' + 'ipt>' );'
		);
	}

	return $polyfill;
}

Hooks

apply_filters( ‘script_loader_src’, string $src, string $handle )

Filters the script loader source.

Changelog

VersionDescription
5.0.0Introduced.

User Contributed Notes

You must log in before being able to contribute a note or feedback.

{“prefetch”:[{“source”:”document”,”where”:{“and”:[{“href_matches”:”/*”},{“not”:{“href_matches”:[“/wp-*.php”,”/wp-admin/*”,”/files/*”,”/wp-content/*”,”/wp-content/plugins/*”,”/wp-content/themes/wporg-developer-2023/*”,”/wp-content/themes/wporg-parent-2021/*”,”/*\?(.+)”]}},{“not”:{“selector_matches”:”a[rel~=”nofollow”]”}},{“not”:{“selector_matches”:”.no-prefetch, .no-prefetch a”}}]},”eagerness”:”conservative”}]} var prism_settings = {“pluginUrl”:”https://developer.wordpress.org/wp-content/plugins/code-syntax-block/”}; //# sourceURL=mkaz-code-syntax-prism-js-js-extra var autocomplete = {“ajaxurl”:”https://developer.wordpress.org/wp-admin/admin-ajax.php”,”nonce”:”f0b06c0625″,”post_type”:”wp-parser-function”}; //# sourceURL=autocomplete-js-extra wp.i18n.setLocaleData( { ‘text directionu0004ltr’: [ ‘ltr’ ] } ); //# sourceURL=wp-i18n-js-after var wporgFunctionReferenceI18n = {“copy”:”Copy”,”copied”:”Code copied”,”expand”:”Expand code”,”collapse”:”Collapse code”,”sourceFile”:”wp-includes/script-loader.php”}; //# sourceURL=wporg-developer-function-reference-js-extra var quicktagsL10n = {“closeAllOpenTags”:”Close all open tags”,”closeTags”:”close tags”,”enterURL”:”Enter the URL”,”enterImageURL”:”Enter the URL of the image”,”enterImageDescription”:”Enter a description of the image”,”textdirection”:”text direction”,”toggleTextdirection”:”Toggle Editor Text Direction”,”dfw”:”Distraction-free writing mode”,”strong”:”Bold”,”strongClose”:”Close bold tag”,”em”:”Italic”,”emClose”:”Close italic tag”,”link”:”Insert link”,”blockquote”:”Blockquote”,”blockquoteClose”:”Close blockquote tag”,”del”:”Deleted text (strikethrough)”,”delClose”:”Close deleted text tag”,”ins”:”Inserted text”,”insClose”:”Close inserted text tag”,”image”:”Insert image”,”ul”:”Bulleted list”,”ulClose”:”Close bulleted list tag”,”ol”:”Numbered list”,”olClose”:”Close numbered list tag”,”li”:”List item”,”liClose”:”Close list item tag”,”code”:”Code”,”codeClose”:”Close code tag”,”more”:”Insert Read More tag”}; //# sourceURL=quicktags-js-extra var wporg_note_feedback = {“show”:”Show feedback”,”hide”:”Hide feedback”,”hide_feedback”:”Hide feedback form”,”add_feedback”:”Add feedback”}; //# sourceURL=wporg-developer-user-notes-feedback-js-extra var wporg_note_preview = {“ajaxurl”:”https://developer.wordpress.org/wp-admin/admin-ajax.php”,”nonce”:”4f43700f72″,”preview”:”preview note”,”preview_empty”:”Nothing to preview”,”is_admin”:””}; //# sourceURL=wporg-developer-preview-js-extra _stq = window._stq || []; _stq.push([ “view”, {“v”:”ext”,”blog”:”209306761″,”post”:”39957″,”tz”:”0″,”srv”:”developer.wordpress.org”,”j”:”1:15.5″} ]); _stq.push([ “clickTrackerInit”, “209306761”, “39957” ]); //# sourceURL=jetpack-stats-js-before var wporgGlobalHeaderI18n = {“openSearchLabel”:”Open Search”,”closeSearchLabel”:”Close Search”,”overflowMenuLabel”:”More menu”}; //# sourceURL=wporg-global-header-script-js-extra {“baseUrl”:”https://s.w.org/images/core/emoji/17.0.2/72×72/”,”ext”:”.png”,”svgUrl”:”https://s.w.org/images/core/emoji/17.0.2/svg/”,”svgExt”:”.svg”,”source”:{“concatemoji”:”https://developer.wordpress.org/wp-includes/js/wp-emoji-release.min.js?ver=7.1-alpha-62239″}} /*! This file is auto-generated */ const a=JSON.parse(document.getElementById(“wp-emoji-settings”).textContent),o=(window._wpemojiSettings=a,”wpEmojiSettingsSupports”),s=[“flag”,”emoji”];function i(e){try{var t={supportTests:e,timestamp:(new Date).valueOf()};sessionStorage.setItem(o,JSON.stringify(t))}catch(e){}}function c(e,t,n){e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(t,0,0);t=new Uint32Array(e.getImageData(0,0,e.canvas.width,e.canvas.height).data);e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(n,0,0);const a=new Uint32Array(e.getImageData(0,0,e.canvas.width,e.canvas.height).data);return t.every((e,t)=>e===a[t])}function p(e,t){e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillText(t,0,0);var n=e.getImageData(16,16,1,1);for(let e=0;e{s[e]=t(o,e,n,a)}),s}function r(e){var t=document.createElement(“script”);t.src=e,t.defer=!0,document.head.appendChild(t)}a.supports={everything:!0,everythingExceptFlag:!0},new Promise(t=>{let n=function(){try{var e=JSON.parse(sessionStorage.getItem(o));if(“object”==typeof e&&”number”==typeof e.timestamp&&(new Date).valueOf(){i(n=e.data),r.terminate(),t(n)})}catch(e){}i(n=f(s,u,c,p))}t(n)}).then(e=>{for(const n in e)a.supports[n]=e[n],a.supports.everything=a.supports.everything&&a.supports[n],”flag”!==n&&(a.supports.everythingExceptFlag=a.supports.everythingExceptFlag&&a.supports[n]);var t;a.supports.everythingExceptFlag=a.supports.everythingExceptFlag&&!a.supports.flag,a.supports.everything||((t=a.source||{}).concatemoji?r(t.concatemoji):t.wpemoji&&t.twemoji&&(r(t.twemoji),r(t.wpemoji)))}); //# sourceURL=https://developer.wordpress.org/wp-includes/js/wp-emoji-loader.min.js