user1884155
user1884155

Reputation: 3736

Iframe doesn't show onload, but it does after manual reload

I'm using an Asp.net/C# environment and Visual Studio 2013 to create a web application.

I have a page (aspx) with only a single iframe in it, and a javascript method that uses jquery to put html into that frame.

<asp:Content runat="server" ID="MainSectionContent" ContentPlaceHolderID="MainSectionContentPlaceHolder">
    <section runat="server" id="FrameSection" clientidmode="Static">
        <asp:ContentPlaceHolder runat="server" ID="FrameSectionContentPlaceHolder" />
        <iframe id="FrameContentFrame" name="FrameContentFrame" src="about:blank" seamless="seamless" onload=" loadFrameContent(); "></iframe>
    </section>

    <script type="text/javascript">
        //<![CDATA[
        function loadFrameContent() {
            jQuery('#FrameContentFrame').contents().find('html').html('<%= FrameContent %>'); //FrameContent is a c# property which holds a syntactically correct html string
        }
        //]]>
    </script>
</asp:Content>

In my code behind I fetch a long string from a server and store it in the property FrameContent. This long strings is syntactically correct html.

The result should be: onload, the javascript method runs. The iframe is populated with html and thus the html string is shown to the user.

but what really happens: nothing is shown. a Javascript error occurs saying "the function loadFrameContent is undefined". But its clearly there if I view the page source in my web browser. If I right click on the blank page where the frame should be, and choose "reload frame" (Google Chrome), the frame does show the Html.

So: the Html string is correct. the frame is correct. the frame can display the html correctly. However, the frame cannot display the Html onload, it needs an additional manual reload to actually show anything! I checked the page source on my browser and the Javascript function IS present, and the FrameContent property is populated with the correct html string.

Upvotes: 0

Views: 964

Answers (1)

Joel Etherton
Joel Etherton

Reputation: 37523

As I see it, it looks like a timing issue. A blank iframe will be finished loading before your parent page, so it will call loadFrameContent before the parent page has finished parsing its dom (thus the method won't be registered). Get rid of the iframe onload and add this:

<script type="text/javascript">
    //<![CDATA[
    function loadFrameContent() {
        jQuery('#FrameContentFrame').contents().find('html').html('<%= FrameContent %>');     //FrameContent is a c# property which holds a syntactically correct html string
    }

    $(loadFrameContent);

    // Or if you're using an older version of jQuery
    //$(document).ready(loadFrameContent);
    //]]>
</script>

Upvotes: 1

Related Questions