我正在开发一个小部件。 它的代码是:
<script type="text/javascript">
var hashgurus_woeid = 1;
</script>
<script src="../feed/livetrend.js"></script>
livetrend.js包含:
var _html = '<div id="FJ_TF_Cont" style="position: relative; padding: 20px; margin: 20px; border-width: 0px; width: 200px;">'
+ '<iframe width="210" height="640" src="../feed/default.aspx?woeid=' + hashgurus_woeid +'" '
+ 'name="FJIframe" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" style="width: 210px; border-width: 0px; z-index: 1;">'
+ '</iframe>'
+ '</div>';
document.write(_html);
测试html页面:
我创建了一个测试html页面并将小部件放入其中。它非常有效。 现在整个问题是我添加async属性。我没有看到任何输出。
<script type="text/javascript">
var hashgurus_woeid = 1;
</script>
<script async src="../feed/livetrend.js"></script>
有什么问题?是因为document.write?
答案 0 :(得分:1)
document.write
。使用常规脚本和异步注入HTML,例如
var div = document.createElement('div');
div.id = "FJ_TF_Cont";
div.style.position = 'relative';
div.style.padding = '20px';
div.style.margin = '20px';
div.style.borderWidth = 0;
div.style.width = '200px';
var div.innerHTML = '<iframe width="210" height="640" src="../feed/default.aspx?woeid=' + hashgurus_woeid +'" '
+ 'name="FJIframe" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" style="width: 210px; border-width: 0px; z-index: 1;">'
+ '</iframe>';
document.body.appendChild(div);
如果要在脚本的位置插入,可以使用:
HTML -
<script async data-hashgurus-woeid="1" id="live-trend-widget" src="../feed/livetrend.js"></script>
使用Javascript -
var liveTrendWidget = document.getElementById('live-trend-widget');
var hashGurusWoeId = liveTrendWidget.getAttribute("data-hashgurus-woeid");
var widgetDiv = document.createElement('div');
widgetDiv.id = "FJ_TF_Cont";
widgetDiv.style.position = 'relative';
widgetDiv.style.padding = '20px';
widgetDiv.style.margin = '20px';
widgetDiv.style.borderWidth = 0;
widgetDiv.style.width = '200px';
widgetDiv.innerHTML = '<iframe width="210" height="640" src="../feed/default.aspx?woeid=' + hashGurusWoeId +'" '
+ 'name="FJIframe" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" style="width: 210px; border-width: 0px; z-index: 1;">'
+ '</iframe>';
// Inserts BEFORE the script element
liveTrendWidget.parentElement.insertBefore(widgetDiv, liveTrendWidget);
// *** OR ***
// Inserts AFTER the script element
liveTrendWidget.parentElement.insertBefore(widgetDiv, liveTrendWidget.nextSibling);