簡體   English   中英

將Twitter Widget的Javascript放入其中 <Head> 標簽,但讓它呈現 <Body>

[英]Putting Twitter Widget's Javascript within <Head> tags, but have it rendered in <Body>

我正在使用Twitter搜索小部件,目前我在HTML的body標簽中嵌入了javascript,如下所示:

<body>
 <script charset="utf-8" src="https://widgets.twimg.com/j/2/widget.js"></script>
 <script>
        new TWTR.Widget({
                  version: 2,
                  type: 'faves',
                  rpp: 1,
                  interval: 7200000,
                  title: '',
                  subject: '',
                  width: 500,
                  height: 65,
                  theme: {
                    shell: {
                      background: '#a4c9b9',
                      color: '#ffffff'
                    },
                    tweets: {
                      background: '#a4c9b9',
                      color: '#ffffff',
                      links: '#444444'
                    }
                  },
                  features: {
                    scrollbar: true,
                    loop: false,
                    live: false,
                    behavior: 'all'
                  }
                }).render().setUser('exampleuser').start();
     </script>
 </body>

相反,我寧願將所有javascript移動到標題(或者可能是頁腳?)標記,然后只是在沒有標記的情況下將其渲染到正文中。 有一個簡單的方法嗎?

你可以使用其中一個本機JS ...

window.onload = function() {
    // your code here
};

或者jQuery ......

$(document).ready(function() {
    // your code here
});

...確保代碼在文檔加載完成之前不會運行。

這解釋了window.onload和$(document).ready()之間的細微差別。

另一個選擇是將代碼包裝在一個命名函數中並在某個地方調用它,但你仍然需要將它放在<script>標記中。

編輯:使用window.onload ...

<html>
<head>
<script>
window.onload = function() {
    new TWTR.Widget({
              version: 2,
              type: 'faves',
              rpp: 1,
              interval: 7200000,
              title: '',
              subject: '',
              width: 500,
              height: 65,
              theme: {
                shell: {
                  background: '#a4c9b9',
                  color: '#ffffff'
                },
                tweets: {
                  background: '#a4c9b9',
                  color: '#ffffff',
                  links: '#444444'
                }
              },
              features: {
                scrollbar: true,
                loop: false,
                live: false,
                behavior: 'all'
              }
            }).render().setUser('exampleuser').start();
};
</script>
</head>
<body></body></html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM