Tontsasd
Tontsasd

Reputation: 33

Refresh div content which contains a script that gets the feed as document.write

I have been trying to do webpage which shows me all kinds of stuff that I use daily. I tried to get a Reddit feed there, which would refresh automatically every x seconds (60 sec or something). But the problem is that the feed comes as

document.write({INSERT FEED HERE});

which is loaded asynchronously and so it gives an error:

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

So is there any way to get this updating by itself, without updating the whole page.

<head>  
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>

<body>
<div id="reddit">
<script>
    $(document).ready(
        function() {
            setInterval(function() {
                reload_js();
            }, 60000);
        });

        function reload_js() {
        var s = document.createElement("script");
        s.type = "text/javascript";
        s.src = "https://www.reddit.com/r/ProgrammerHumor/new/.embed?limit=10&t=all";
        document.getElementById("reddit").appendChild(s);
    }
    </script>
</div>
</body>

This is the simple page I have right now for the reddit feed.

Upvotes: 0

Views: 62

Answers (1)

Robiseb
Robiseb

Reputation: 1606

By default, the .embed webservice use document.write if no callback parameter is defined.

Just add a callback parameter, like this https://www.reddit.com/r/ProgrammerHumor/new/.embed?limit=10&t=all&callback=yourFunction

And add a yourFunction function that will append the content

function yourFunction(data) {
  document.getElementById("reddit").appendChild(data);
}

Enjoy :)

Upvotes: 3

Related Questions