Home  >  Article  >  Web Front-end  >  快速掌握WordPress中加载JavaScript脚本的方法_javascript技巧

快速掌握WordPress中加载JavaScript脚本的方法_javascript技巧

WBOY
WBOYOriginal
2016-05-16 15:24:571691browse

在 WordPress 中加载脚本(为 CSS 和 JS,下同)文件,大多数人的做法是直接在 header.php 文件中添加 link 标签,或者把 link 标签通过 wp_head 钩子直接添加到 head 标签里,这种做法是不符合官方规范的。

标准的脚本加载方式应该是使用 WordPress 官方提供的函数(后边会说),统一标准有几个好处,首先就是更加安全和利于管理,其次是更加的方便快捷,而且不仅主题能挂载脚本,插件也可以,并且还能管理脚本,并且调整挂载顺序和位置和其它内容。

在哪个钩子加载?

在调用加载脚本函数之前,我们首先要确定函数在哪个钩子处执行,有四个常用的脚本加载钩子,分别是 wp_enqueue_scripts(在前台加载)、admin_enqueue_scripts(在后台加载)、login_enqueue_scripts(在登录页加载)和 init(全局加载)。

最常用的应该是 wp_enqueue_scripts 了,挂载到这上面,脚本只在前台加载。

加载 JavaScript 脚本

比如说我想在前台加载一个 JS,是主题根目录 JS 文件夹的 themes.js 文件。首先需要使用 wp_register_script() 函数把 JS 添加到脚本库里边(注册脚本),然后再使用 wp_enqueue_script() 函数挂载脚本。

function Bing_enqueue_scripts(){
  wp_register_script( 'themes_js', get_bloginfo( 'template_directory' ) . '/js/themes_js.js' );//注册 ID 为 themes_js 的 JS 脚本
  wp_enqueue_script( 'themes_js' );//挂载脚本
}
add_action( 'wp_enqueue_scripts', 'Bing_enqueue_scripts' );

加载 CSS 脚本

function Bing_enqueue_scripts(){
  wp_register_style( 'style', get_bloginfo( 'template_directory' ) . '/style.css' );
  wp_enqueue_style( 'style' );
}
add_action( 'wp_enqueue_scripts', 'Bing_enqueue_scripts' );

小结

本文只是非常简单的讲解了怎么加载脚本,合理的利用脚本排队机制,可以让程序变得灵活,也可以加快效率。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn