Jared Caputo Jared Caputo - 6 months ago 78
Javascript Question

JQuery to load div after page is completely loaded is not working in Chrome, but is in Safari and Firefox

I'm using the code below (JQuery) to delay the loading of a div until after the entire page has loaded (code, images, etc and rendered). It is working in Safari and Firefox, but not in Chrome. On Safari and Firefox, the web page loads and renders everything, and then it loads the div (the Facebook embed) after the browser says everything is loaded (loader stops spinning, page content is shown, browsers developer tools say everything is loaded -- not just DOM). In Chrome, though, it just loads at the end (after DOM content) but before everything is loaded and shown (like it does in Safari and Firefox, which is how it is supposed to and how I want it to work). I would greatly appreciate any help on making this work in Chrome like it does in the other browsers! (I asked yesterday, but the answer I was provided didn't fix the issue for me, and I perhaps wasn't clear about what I wanted (perhaps mistaken for only after DOM was loaded) so I decided to put it up again so it was more clear.)

<script type="text/javascript">

function insertFB(){
var html='<div class="fb-page" data-href="https://www.facebook.com/bobcaputolivingwell" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true" data-show-posts="true"><div class="fb-xfbml-parse-ignore"><blockquote cite="https://www.facebook.com/bobcaputolivingwell"><a href="https://www.facebook.com/bobcaputolivingwell">Bob Caputo Living Well</a></blockquote></div></div>';
$("#FB_PAGE").html(html);
}

if (document.addEventListener){
document.addEventListener("DOMContentLoaded", insertFB, false);
}

if (/WebKit/i.test(navigator.userAgent)){
var _timer = setInterval(function(){
if(/loaded|complete/.test(document.readyState)){
insertFB;
}
},10);
}

window.onload = insertFB();

</script>

Answer

You're essentially triggering that function 3 times in browsers such as Chrome/Safari. All you need is the following.

function insertFB() {
    var html = '<div class="fb-page" data-href="https://www.facebook.com/bobcaputolivingwell" data-small-header="false" data-adapt-container-width="true" data-hide-cover="false" data-show-facepile="true" data-show-posts="true"><div class="fb-xfbml-parse-ignore"><blockquote cite="https://www.facebook.com/bobcaputolivingwell"><a href="https://www.facebook.com/bobcaputolivingwell">Bob Caputo Living Well</a></blockquote></div></div>';
    $("#FB_PAGE").html(html);
}

$(window).on("load", insertFB);

The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.