Ok, lets think we are making a wordpress theme. We have a lot of javascript module like sliders or carousels or ajax loading elements or form controls etc. My main approach for this put the all javascript codes into the main.js files. In main.js i have a code something like this;
好吧,让我们想想我们正在制作一个wordpress主题。我们有很多javascript模块,如滑块或轮播或ajax加载元素或表单控件等。我的主要方法是将所有javascript代码放入main.js文件中。在main.js中,我有一个像这样的代码;
$(".slider").startSlider();
And i import main.js to all pages. So if one of the pages has element which is class is "slider" they work perfectly. But i am curious about this is the true approach or not? If you not use any javascript module in your page still all javascript codes importing your page. Do you have any different approach?
我将main.js导入所有页面。因此,如果其中一个页面具有类是“滑块”的元素,则它们可以完美地工作。但我很好奇这是真的方法吗?如果您在页面中没有使用任何javascript模块,那么所有javascript代码都会导入您的页面。你有什么不同的方法吗?
2 个解决方案
#1
0
You could do
你可以做到
if ($(".slider").length>0) {
jQuery.getScript("slider.js")
.done(function() {
$(".slider").startSlider();
});
}
#2
-1
You really need to get familiar with how wp_enqueue_script()
works so you can add scripts from within your theme functions on an as needed basis.
您真的需要熟悉wp_enqueue_script()的工作原理,以便您可以根据需要在主题函数中添加脚本。
For your slider example you can then add the needed scripts from within template functions or shortcode functions
对于滑块示例,您可以在模板函数或短代码函数中添加所需的脚本
Reference : wp_enqueue_script docs
参考:wp_enqueue_script docs
#1
0
You could do
你可以做到
if ($(".slider").length>0) {
jQuery.getScript("slider.js")
.done(function() {
$(".slider").startSlider();
});
}
#2
-1
You really need to get familiar with how wp_enqueue_script()
works so you can add scripts from within your theme functions on an as needed basis.
您真的需要熟悉wp_enqueue_script()的工作原理,以便您可以根据需要在主题函数中添加脚本。
For your slider example you can then add the needed scripts from within template functions or shortcode functions
对于滑块示例,您可以在模板函数或短代码函数中添加所需的脚本
Reference : wp_enqueue_script docs
参考:wp_enqueue_script docs