WordPress如何只在主页加载JavaScript

我的主页有一个Slideshow,这个slideshow需要加载一个jquery脚本才能正常显示。但其他的页面没有slideshow,所以其他的页面不需要加载这个jquery脚本。但我的wordpress主题默认在所有页面都加载这个jquery脚本,这个脚本有110K。所以,我需要修改一点代码,让这个脚本只在主页加载。

代码

下面这一段代码检测页面是否为主页,如果是主页就加载<script>标签里的脚本。如果不是主页,那么显示“ This is not the homepage”消息。

<?php if( is_home() ) { ?>
    <script>
       content
    </script> 
<?php } else {
    echo 'This is not the homepage';
}
?>

其实这个方法也适用于其他文件,如CSS文件。

<?php if( is_home() ) { ?>
    <link rel="stylesheet" type="text/css" href="home.css" /> 
<?php } else { ?>
    <link rel="stylesheet" type="text/css" href="inner-page.css" /> 
<?php } ?>
你也可以删掉else后面的代码。

效果

你可以在 https://varvy.com/tools/js/ 网站上检测网页中有多少个外部JavaScript文件。也可以在网页源码中查看是否少加载了一个JavaScript文件。

在使用上面的代码之前,我的文章页面大小为543K,

使用上面的代码之后,文章页面就少加载了一个JavaScript,这时大小为433K。

为这篇文章评分
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published.

The maximum upload file size: 2 MB. You can upload: image, audio, video, document, spreadsheet, interactive, text, archive, code, other. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here