Search code examples
javascripthtmlweb-componenthtml-imports

Are importing nodes not added as async to DOM


I remember reading somewhere that if a script tag is added to DOM using appendChild it's not blocking and behaves as if it had async attribute. Today I was reading this article and it has the following code snippet:

var link = document.createElement('link');
link.rel = 'import';
link.href = 'file.html';
//link.setAttribute('async', ''); // make it async!

So I'm wondering isn't the behavior described for script tag the same for link tag? Why add async attribute manually?


Solution

  • As defined in the specification, every <link rel="import> tag not marked as async is blocking the parser.

    If you add the <link> with appendChild(), it doesn't block the current script execution but in fact it will block the parsing until the imported document is loaded.

    If after that you add another tag -with appendChild()- who is referenced by the imported document, you still need to specify the async attribute.

    document.head.appendChild( link )
    //link should be async if it uses the element below:
    document.body.appendChild( element )