在Web上,有许多文章介绍如何使用wp_enqueue_script()
方法。
在这些文章中,我找不到任何解释如何添加内联的内容,<script>
标记封闭的脚本。
我使用<script>
虽然我认为这样做不是最优雅的方式,但我的文档中间的标签。应该有更好的方法来添加任意脚本,以便代码在头部或底部自动移动。有吗?
在Web上,有许多文章介绍如何使用wp_enqueue_script()
方法。
在这些文章中,我找不到任何解释如何添加内联的内容,<script>
标记封闭的脚本。
我使用<script>
虽然我认为这样做不是最优雅的方式,但我的文档中间的标签。应该有更好的方法来添加任意脚本,以便代码在头部或底部自动移动。有吗?
您可以使用wp_add_inline_script 作用
function prince_scripts() {
wp_enqueue_script( \'prince-script\', get_template_directory_uri(). \'main.js\');
$hide_on_mobile = apply_filters( \'prince_hide_on_mobile\', true );
$data = \'var hideOnMobile = \' . ( $hide_on_mobile ? \'true\': \'false\' ) . \';\';
wp_add_inline_script( \'prince-script\', $data, \'before\' );
}
add_action( \'wp_enqueue_scripts\', \'prince_scripts\');
我在看217号functions.php
他们在那里留下了一个内联模式script
(或与此相关的任何内容)以优先顺序输入到文档中,此处使用命名函数概括显示:
function add_inline_script() {
echo "<script>/* do awesome things */</script>\\n";
}
add_action( \'wp_head\', \'add_inline_script\', 0 );
例如,如果正在加载async
类似Google Analytics的脚本async tracking snippet, 使您能够启动non-blocking script requests 一旦文档开始被解析(如果放在阻塞请求之上)。此外async
, 现代浏览器还允许我们manage async dependencies 利用Fetch API, 使人能够load external dependencies 异步并行而不冒竞争条件的风险。
下图和示例说明了如何使用此技术减少页面加载时间loading scripts without blocking 在Twenty Eleven theme 使用Fetch Inject:
Figure 1: 2017个主题脚本外加
lazysizes
并行异步加载。
背驮在question about string interpolation. 放下时使用arbitrary blocks of content 使用进入页面echo
使用NOWDOC或HEREDOC和global
使用Fetch Inject进行赋值和字符串插值,如下所示:
/**
* Load scripts using Fetch Inject instead of wp_enqueue_script
* for for faster page loads and lower perceived latency.
*
* @since WordCamp Ubud 2017
* @link https://wordpress.stackexchange.com/a/263733/117731
* @link https://github.com/jhabdas/fetch-inject
*
*/
function add_inline_script() {
$twentyseventeen_l10n = array(
\'quote\' => twentyseventeen_get_svg( array( \'icon\' => \'quote-right\' ) ),
\'expand\' => __( \'Expand child menu\', \'twentyseventeen\' ),
\'collapse\' => __( \'Collapse child menu\', \'twentyseventeen\' ),
\'icon\' => twentyseventeen_get_svg( array( \'icon\' => \'angle-down\', \'fallback\' => true ) )
);
$jquery_script_path = \'/wp-includes/js/jquery/jquery.js?ver=1.12.4\';
$jquery_dependent_script_paths = [
get_theme_file_uri( \'/assets/js/global.js\' ),
get_theme_file_uri( \'/assets/js/jquery.scrollTo.js\' ),
get_theme_file_uri( \'/assets/js/skip-link-focus-fix.js\' ),
get_theme_file_uri( \'/assets/js/navigation.js\' )
];
$lazysizes_path = get_theme_file_uri( \'/assets/js/lazysizes.min.js\' );
$screen_reader_text_object_name = \'twentyseventeenScreenReaderText\';
$twentyseventeen_l10n_data_json = json_encode($twentyseventeen_l10n);
$jquery_dependent_script_paths_json = json_encode($jquery_dependent_script_paths);
$inline_script = <<<EOD
window.{$screen_reader_text_object_name} = $twentyseventeen_l10n_data_json;
(function () {
\'use strict\';
if (!window.fetch) return;
/**
* Fetch Inject v1.6.8
* Copyright (c) 2017 Josh Habdas
* @licence ISC
*/
var fetchInject=function(){"use strict";const e=function(e,t,n,r,o,i,c){i=t.createElement(n),c=t.getElementsByTagName(n)[0],i.type=r.blob.type,i.appendChild(t.createTextNode(r.text)),i.onload=o(r),c?c.parentNode.insertBefore(i,c):t.head.appendChild(i)},t=function(t,n){if(!t||!Array.isArray(t))return Promise.reject(new Error("`inputs` must be an array"));if(n&&!(n instanceof Promise))return Promise.reject(new Error("`promise` must be a promise"));const r=[],o=n?[].concat(n):[],i=[];return t.forEach(e=>o.push(window.fetch(e).then(e=>{return[e.clone().text(),e.blob()]}).then(e=>{return Promise.all(e).then(e=>{r.push({text:e[0],blob:e[1]})})}))),Promise.all(o).then(()=>{return r.forEach(t=>{i.push({then:n=>{"text/css"===t.blob.type?e(window,document,"style",t,n):e(window,document,"script",t,n)}})}),Promise.all(i)})};return t}();
fetchInject(
$jquery_dependent_script_paths_json
, fetchInject([
"{$jquery_script_path}"
]));
fetchInject(["{$lazysizes_path}"])
})();
EOD;
echo "<script>{$inline_script}</script>";
}
add_action(\'wp_head\', \'add_inline_script\', 0);
将库存2017主题的感知延迟减少约50%。可以应用于任何主题。它是如何工作的?
替换all 已排队的脚本的wp_enqueue_script
因此,通过使用Fetch注入,它们的输出速度更快。(注意:有关与旧浏览器的向后浏览器兼容性,请参阅获取注入文档。)使用HEREDOC以script
中的标记head
.window 范围
如果要确保项目只添加一次,请参阅以下答案:https://wordpress.stackexchange.com/a/131640/117731
最后,如果你想add to the footer 代替头部,您可以替换wp_head
在add_action
使用呼叫wp_footer
.
EDIT: 经过进一步挖掘,我发现this post 在DavidWalsh的博客上,他建议至少从2012年起就可以使用简单的内联。玩得高兴
wp_enqueue_script()
是将javascript添加到站点的唯一方法。它允许您和其他插件声明依赖项,甚至在需要时取消注册脚本。如上所述a different thread 今天,如果你不使用合适的WordPress技术,缓存插件就无法gzip或缩小你的脚本。
如果查看codex页面,您将看到可以控制脚本是在页眉还是页脚中。
尽管mrwweb是正确的,并且应该使用该技术,但实际上没有什么是完美的,有时会使用内联脚本和样式。您可以使用wp script is
要检查脚本并在页眉或页脚中输出它们,请使用wp_head
或wp_footer
.
你可以在这篇文章中参考scribu的答案,wp enqueue inline script due to dependancies
我现在正在使用以下代码进行操作:function uw_load_scripts() { // De-register the built in jQuery wp_deregister_script(\'jquery\'); // Register the CDN version wp_register_script(\'jquery\', \'http://ajax.googleapis.com/ajax/libs/jquery/1.7.