AJAX用于加载代码

Some days ago I came across with Polymer project and web components. It is said to be the future of the web. I do not know much about this. But if I understood well, the idea is to enhance the web code modularity. I would like to ask a simple question, at this respect.

Is there any disadvantage or objection to use AJAX in order to read a presuntly "plain text" file (but with HTML, CSS and JS) and use the "document.write" JavaScript function for inserting that code into a different file? I wondered this, because this seems to solve web code modularity in a very easy and fast way. Is there any problem in doing that?

Thank you!

There is no problem doing that, except document.write won't work after the page has loaded but it is common usage to do something like this to load scripts at runtime:

function addScript(anUrl) {
    var aScript = document.createElement( 'script' );
    aScript.type = 'text/javascript';
    aScript.src = anUrl;
    $("head").append( aScript );
}

The browser will take care of loading and running the script from the url, so you do not need to insert the source manually, but if you need, you can do this way:

function addScriptSource(sourceText) {
    var aScript = document.createElement( 'script' );
    aScript.type = 'text/javascript';
    aScript.textContent = sourceText;
    $("head").append( aScript );
}

The general principle is fine, but certainly using document.write is terrible. document.write cannot be safely used after the document is fully parsed. Therefore, it will be unsafe to use after an asynchronous load of a resource.

A much better approach is to create a DOM node, load the fetched resource into the node, and then load the node into DOM. For example, asynchronously loading a script (but the general principle is generalizable to other resources as well):

var xhr = new XMLHttpRequest();
xhr.open("GET", "somescript.js");
xhr.send();

xhr.addEventListener("load", function(e) {
    var fetchedScriptContent = e.target.responseText

    var s = document.createElement("script");
    s.textContent = fetchedScriptContent;
    // s.innerText = fetchedScriptContent; // for older browsers
    document.body.appendChild(s);
});