如何在Tumblr博客上的每个非索引页面添加JavaScript?

Eri*_*bow 14 javascript tumblr tumblr-themes

我想在我的Tumblr博客上为每个帖子页面添加JavaScript代码.我有以下,但它似乎从来没有出现单独让任何页面上固定链接或个别帖子页.我在这里尝试了许多变体,删除Posts块或PermalinkPage块无济于事.我在这做错了什么?

<!-- Start JS -->
{block:Posts}
    {block:PermalinkPage}
    <script type='text/javascript'>
    __config = {
            {block:Date},date:'{Year}-{MonthNumberWithZero}-{DayOfMonthWithZero} {24HourWithZero}:{Minutes}:{Seconds}'{/block:Date}
            {block:PostSummary},title:{JSPlaintextPostSummary}{/block:PostSummary}
            {block:HasTags},tags:[{block:Tags}'{Tag}', {/block:Tags}],{/block:HasTags}
            ,url:'{URLEncodedPermalink}'
    };
    (function(){
      var s = document.createElement('script');
      s.type = 'text/javascript';
      s.src = document.location.protocol + '//example.com/example.js';
      (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
    })();
    </script>
    {/block:PermalinkPage}
{/block:Posts}
<!-- END JS -->
Run Code Online (Sandbox Code Playgroud)

lha*_*rby 9

这就是我使用JavaScript /前端解决它的方法.

var path = document.location.pathname;
path = path.split("/")[1]; // Should return the primary directory
path = path.toLowerCase(); // This should catch your.tumblr.com/Search and your.tumblr.com/search
if(path === "" || path === "search")){
    console.log('Index or Search page');
}else{
   // Run your function here
}
Run Code Online (Sandbox Code Playgroud)

基本上,如果路径URL为空或等于,search则不运行该函数,但在任何其他情况下运行该函数.

但是,正如我所提到的,这不是100%强大.由于路径可能http://your.tumblr.com/#并且函数将失败,因此您可能必须构建更明确的逻辑(您可以说是否path !== " "为空字符串).

我仍然不确定为什么在每一页上都有这个不是一个好主意.除非用户肯定被链接到网站上的页面,并且没有通过索引页面进行路由.除非您的JavaScript代码很大,否则它们都可以从索引页面缓存(但在热链接的情况下仍可从所有其他页面获得,等等).

编辑

根据下面的评论,我在测试Tumblr帐户上创建了一个基本示例.

代码如下所示:

  var path = document.location.pathname;
  path = path.split("/")[1];
  path = path.toLowerCase();
  if(path === "" || path === "about"){
    $('body').css('background','#F09');
    console.log('Index or about page');
  }else{
    $('body').css('background','#FC0');
    console.log('Other page');
  }
Run Code Online (Sandbox Code Playgroud)

我正在使用的Tumblr页面在这里:http://sg-test.tumblr.com/

(我认为没有搜索页面,搜索功能是您在模板中插入或激活的块,并且在每个页面上都可用.)

该函数基本上检查索引页面(空主目录)或about页面(如果需要,将其替换为'search'或其他页面).

控制台日志将在每个页面上输出.如果路径匹配索引或关于我已将主体颜色设置为粉红色,或者每隔一个页面将为橙色.

http://sg-test.tumblr.com/about (粉红色背景)

http://sg-test.tumblr.com/post/134796799695/post-title (橙色背景)

通过这种逻辑,如果满足路径变量要求,应该很容易调整函数来执行代码,如我的第一个例子中所示.

正如我所提到的,虽然http://sg-test.tumblr.com/#存在问题.这实际上仍然是索引页面,但我们的测试对于空目录返回false,即使Tumblr将其映射到主页.