KamalSalem
KamalSalem

Reputation: 495

Load external html into a div - page loads then goes blank

I'm sure this is going to turn out to be a stupid thing but here goes since I'm a JavaScript noob.

I'm trying to load the contents of an external html into my index page, so in my index.html I have this div into which I want to load the html:

<div id="topdiv">
</div><script>
        $('#topdiv').load("/widgets/2-0.html");
</script>`

And here are the contents of 2-0.html that I'm trying to load, it loads on itself in a browser, I have 3 of this control (the official twitter widget):

<div style="float:right; margin:5px;">
    <script src="http://widgets.twimg.com/j/2/widget.js"></script>
    <script>
        new TWTR.Widget({  version: 2,  type: 'search',  search: '#abbaseya',  interval: 15000,  subject: 'widget',  width: 300,  height: 360,
        theme: {    shell: {      background: '#8ec1da',      color: '#ffffff'    },
        tweets: {      background: '#ffffff',      color: '#444444',      links: '#1985b5'    }  },
        features: {    scrollbar: true,    loop: true,    live: true,    behavior: 'default'  }
        }).render().start();
    </script>
</div>

But I can't get it to load into my div on the index.html page. Can anyone help?

EDIT1: I tried to modify the div and put the script AFTER the div has been loaded

<div id="topdiv" style="height:500px;width:100%;">


        </div>
        <script>$('#topdiv').load("/widgets/2-0.html");</script>

and I put the two files under the same folder, now what happens is, the page loads, I can see it for a couple of seconds, then everything goes blank and I'm presented with a blank white screen. I tried to view page source, I can see the div elements, and they are empty, and everything else is the same exact way

EDIT2: I put the .load function in the $(document).ready function, now when the page loads, the external html replaces my index.html completely

Upvotes: 0

Views: 3199

Answers (2)

Luis Perez
Luis Perez

Reputation: 28120

I believe the widget uses document.write() to render itself which means it has to be called while the page is rendering, that is it has to be called before the page loads.

Calling document.write() after the page loads causes the whole page to be rewritten.

You could potentially rewrite the JavaScript for the widget itself so that it doesn't use document.write() but that might take some effort.

If you have the option you can use a server side include instead of trying to load an external file with JavaScript.

Upvotes: 1

Ry-
Ry-

Reputation: 224942

Your script is executing before #topdiv exists. You should either put it after the <div> or just use a handler:

$(document).ready(function() {
    $('#topdiv').load("/widgets/2-0.html");
});

Upvotes: 4

Related Questions