Search code examples
jqueryphp-include

jquery noConflict not working in php include()


jquery.noConflict doesnt work for some reason when loading from an exernal file using php includes? aslo noticed that maybe some scripts arent fully loading as well?


mainfile.php

<script type="text/javascript" src="js.jquery/jquery.1.8.2.min.js"></script>

<?
include 'extrn_file.php';
?>

// end

//extrn_file.php

<script type="text/javascript" src="js.jquery/jquery.1.3.2.min.js"></script>
<script> $jq132 = jQuery.noConflict(true); </script>
<script type="text/javascript" src="js/animate.js"></script>

<script type="text/javascript">
execute_skills_doc();

function execute_skills_doc(){
$jq132(document).ready(function() {
alert("yes");//nothing happens
});

}

//end


Solution

  • If you want to use multiple version of jQuery on the same page you have to noConflict() the first before you load the second. Since your PHP include just pulls the contents of the two files together, you are ending up with:

    <script type="text/javascript" src="js.jquery/jquery.1.8.2.min.js"></script>
    <script type="text/javascript" src="js.jquery/jquery.1.3.2.min.js"></script>
    <script> $jq132 = jQuery.noConflict(true); </script>
    

    What you really want would be:

    <script type="text/javascript" src="js.jquery/jquery.1.8.2.min.js"></script>
    <script type="text/javascript"> 
        // set version 1.8.2 to variable and remove globals
        $jq182 = jQuery.noConflict(true); 
    </script>
    <script type="text/javascript" src="js.jquery/jquery.1.3.2.min.js"></script>
    <script type="text/javascript">
        // return jQuery version
        function getVersion(jq){
            return jq().jquery;
        }
    
        // set version 1.3.2 to variable and remove globals
        $jq132 = jQuery.noConflict(true); 
        // reset jQuery variable to 1.8.2
        jQuery = $jq182.noConflict();
    
        // your code that uses $ variable and jQuery 1.3.2
        (function($){
            $(document).ready(function(){ alert('Using $ v'+getVersion($)+'!'); });
        })($jq132);
    
        // your code that uses $ variable and jQuery 1.8.2
        (function($){
            $(document).ready(function(){ alert('Using $ v'+getVersion($)+'!'); });
        })($jq182);
    
        // your code that uses jQuery variable and jQuery 1.8.2
        jQuery(document).ready(function(){ alert('Using jQuery v'+getVersion(jQuery)+'!'); });
    
    </script>​
    

    At this point you will have version 1.8.2 loaded into the $jq182 and jQuery variables and 1.3.2 loaded into the $jq132 variable. The code above will alert the variable used and version of each. You can see an example using the Google API hosted libraries here: http://jsfiddle.net/2kX3E/