Javascript 将脚本动态添加到某些页面
我有一个Wordpress网站,显然是模板驱动的。如果我想在特定页面上加载脚本,我需要添加什么javascript?最好由URL定义(除非有更好的方法?)Javascript 将脚本动态添加到某些页面,javascript,wordpress,Javascript,Wordpress,我有一个Wordpress网站,显然是模板驱动的。如果我想在特定页面上加载脚本,我需要添加什么javascript?最好由URL定义(除非有更好的方法?) IE:仅当URL=“abc.net/123”您可以使用以下内容时加载脚本: if (window.location.href.indexOf('abc.net/123') != -1) { document.write('<script src="foo.js"><\/script>'); } if(window
IE:仅当URL=“abc.net/123”您可以使用以下内容时加载脚本:
if (window.location.href.indexOf('abc.net/123') != -1) {
document.write('<script src="foo.js"><\/script>');
}
if(window.location.href.indexOf('abc.net/123')!=-1){
文件。写(“”);
}
因此,只有当位置包含“abc.net/123”时,才会添加脚本元素
但是,如果您控制服务器,那么最好在那里包含脚本
wp_enqueue_脚本是将以下项目排入队列时使用的适当挂钩:
将出现在前端。尽管名称不同,但它用于
将脚本和样式排队
在WordPress
中,您可以使用函数动态添加任何脚本
在带有挂钩的前端上。例如:
function my_scripts_method() {
wp_enqueue_script(
'custom-script', // script identifier
get_stylesheet_directory_uri() . '/js/custom_script.js', // path
array( 'jquery' ) // dependency
);
}
// Register the handler
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
要检测页面(page/post),WordPress
中有许多可用的函数,但是您的url
,即abc.com/123
似乎不适合这些函数(是home()
,是single()
等),或者我不确定这是什么页面,所以我会使用这样的东西:
$Page = $_SERVER['REQUEST_URI'];
if ($page == 123) { // or '123' and only REQUEST_URI
//add script
}
因此,将此代码粘贴到主题的functions.php
文件中:
function my_scripts_method() {
$Page = $_SERVER['REQUEST_URI'];
if ($page == 123) { // or '123'
wp_enqueue_script('...'); // provide required args
}
}
// Register the handler
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
阅读答案中提供的链接了解更多信息