FYIStudio
FYIStudio

Reputation: 11

Javascript behaving inconsistently with PHP include files

I have a very simple javascript animation that looks like this

$(function() {
$('#slider1').cycle();
$('#slider2').cycle();
});

Im then calling in this script like this into my head:

<script type="text/javascript" src="js/slider.js"></script>

Then the divs that have the id "slider1" and "slider2" are contained in php include files being called into the page like this:

<?php include('assets/col1.php'); ?>

The code in the include file looks like this:

<div id="slider1">
<img src="images/image1.png" />
<img src="images/imgae2.png" />
<img src="images/image3.png" />
<img src="images/image4.png" />
</div>

Which works fine except when you get to IE8 or IE9. The javascript will work about 75% of the time which is why this has me baffled. When you load the page or come back to the page, every once in awhile it just doesn't activate the javascript and all the images render in one long column (essentially what it looks like with no js function)

I suspect its something in the order in which IE9 is loading the PHP and the javascript but I am only a novice in both js and php so some very clear help on how to fix this would be really great. Thanks in advance.

Upvotes: 1

Views: 122

Answers (2)

rgamber
rgamber

Reputation: 5849

I had encountered a similar issue while using Dojo, which I solved as follows: Set the main or the parent div display style as none:

<div id="g_body" style="display:none">

Now once Dojo finishes loading, I change the display style to block using the dojo.ready function:

require(["dojo/ready", "dojo/parser", "dijit/registry"], function(ready, parser, registry){
  ready(function(){
    if(document.getElementById("g_body")!= null){
        document.getElementById("g_body").setAttribute("style","display:block");
    }
  });
});

The pages then only shows when Dojo elements are completely loaded.

I believe there is something similar in jQuery, but I am not sure. Probably:

$(document).ready(function() {});

Hope this helps.

Upvotes: 0

Mike Mackintosh
Mike Mackintosh

Reputation: 14237

Soooo long story long...

PHP will return interpreted HTML. Every time you include a file, PHP will flush the buffers, which means, certain content is returned to the browser prior to others. While this happens, the page is still in a loading state.

For this reason, you need to make sure you call $(document).ready(function(e){ ... });. This will give you code a chance to finish flushing the buffers and load into the browser, before the javascript is executed..

Upvotes: 1

Related Questions