user4542866
user4542866

Reputation:

javascript <script async attribute>

I am developing a widget. the code for it is :

<script type="text/javascript">
    var hashgurus_woeid = 1;
</script>
<script src="../feed/livetrend.js"></script>

livetrend.js contains:

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);

test html page:

I created a test html page and put the widget in it. It perfectly works. Now the whole problem is when i add the async attribute. i donot see any output.

<script type="text/javascript">
    var hashgurus_woeid = 1;
</script>
<script async src="../feed/livetrend.js"></script>

what is the problem ? is it because of the document.write ?

Upvotes: 0

Views: 323

Answers (1)

user488187
user488187

Reputation:

document.write cannot be called from an asynchronous script. Use a regular script and an asynchronous injection of the HTML instead, e.g.

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);

If you want to insert at the point of the script, you can use:

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);

See getAttribute method and insertBefore method.

Upvotes: 1

Related Questions