最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - document.write() and Ajax - Doesn't work, looking for an alternative - Stack Overflow

programmeradmin0浏览0评论

I recently asked a question here, and received a great response (which I will shortly be accepting the most active answer of, barring better alternatives arise) but unfortunately it seems the of the two options suggested, neither will be patible with Ajax (or any dynamically added content that includes such "inline-relative jQuery")

Anyways, my question pertains to good ole' document.write().

While a page is still rendering, it works great; not so much when an appended snippet contains it. Are there any alternatives that won't destroy the existing page content, yet still append a string inline, as in where the call is occurring?

In other words, is there a way/alternative to document.write() that when called post-render, doesn't destroy existing page content? An Ajax friendly version so to speak?


This is where I'm going:

var _inline_relative_index = 0;
function $_inlineRelative(){
    // i hate non-dedicated string concatenation operators
    var inline_relative_id = ('_inline_relative_{index}').replace('{index}', (++_inline_relative_index).toString());
    document.write(('<br id="{id}" />').replace('{id}', inline_relative_id));
    return $(document.getElementById(inline_relative_id)).remove().prev('script');
}

And then:

<div>
    <script type="text/javascript">
        (function($script){
            // the container <div> background is now red.
            $script.parent().css({ 'background-color': '#f00' });
        })($_inlineRelative());
    </script>
</div>

I recently asked a question here, and received a great response (which I will shortly be accepting the most active answer of, barring better alternatives arise) but unfortunately it seems the of the two options suggested, neither will be patible with Ajax (or any dynamically added content that includes such "inline-relative jQuery")

Anyways, my question pertains to good ole' document.write().

While a page is still rendering, it works great; not so much when an appended snippet contains it. Are there any alternatives that won't destroy the existing page content, yet still append a string inline, as in where the call is occurring?

In other words, is there a way/alternative to document.write() that when called post-render, doesn't destroy existing page content? An Ajax friendly version so to speak?


This is where I'm going:

var _inline_relative_index = 0;
function $_inlineRelative(){
    // i hate non-dedicated string concatenation operators
    var inline_relative_id = ('_inline_relative_{index}').replace('{index}', (++_inline_relative_index).toString());
    document.write(('<br id="{id}" />').replace('{id}', inline_relative_id));
    return $(document.getElementById(inline_relative_id)).remove().prev('script');
}

And then:

<div>
    <script type="text/javascript">
        (function($script){
            // the container <div> background is now red.
            $script.parent().css({ 'background-color': '#f00' });
        })($_inlineRelative());
    </script>
</div>
Share Improve this question edited May 23, 2017 at 11:47 CommunityBot 11 silver badge asked Sep 22, 2011 at 3:48 Dan LuggDan Lugg 20.7k19 gold badges115 silver badges179 bronze badges 5
  • Where in the already-rendered document do you want it to appear? – ceejayoz Commented Sep 22, 2011 at 3:52
  • @ceejayoz - Immediately following the <script> tag; I'll provide an example. – Dan Lugg Commented Sep 22, 2011 at 3:53
  • Put an empty <div> right after the script tag and use jQuery's appendTo to add stuff to it. – ceejayoz Commented Sep 22, 2011 at 3:55
  • @ceejayoz - Unfortunately, that's not feasible. The script needs to be unaware of the existing DOM. This is why document.write() was so perfect, but I hadn't realized the Ajax caveat. – Dan Lugg Commented Sep 22, 2011 at 4:05
  • What code do you use to load scripts via Ajax? I'm pretty sure it adds the script as the last child node of document.head, so $('head>script:last') together with readyState should be the way to go. – user123444555621 Commented Sep 22, 2011 at 4:31
Add a ment  | 

2 Answers 2

Reset to default 4

you have access to the innerHTML property of each DOM node. If you set it straight out you might destroy elements, but if you append more HTML to it, it'll preserve the existing HTML.

document.body.innerHTML += '<div id="foo">bar baz</div>';

There are all sorts of nuances to the sledgehammer that is innerHTML, so I highly remend using a library such as jQuery to normalize everything for you.

You can assign id to the script tag and replace it with the new node.

<p>Foo</p>
<script type="text/javascript" id="placeholder">
    var newElement = document.createElement('div');
    newElement.id='bar';
    var oldElement = document.getElementById('placeholder');
    oldElement.parentNode.replaceChild(newElement, oldElement);
</script>
<p>Baz</p>

And if you need to insert html from string, than you can do it like so:

var div = document.createElement('div');
div.innerHTML = '<div id="bar"></div>';
var placeholder = document.getElementById('placeholder'), 
    container = placeholder.parentNode,
    elems = div.childNodes, 
    el;
while (el = elems[0]) {
    div.removeChild(el);
    container.insertBefore(el, placeholder);
}
container.removeChild(placeholder);
发布评论

评论列表(0)

  1. 暂无评论