0

I've made an ajax #container div with php include:

<div id="container">
    <?php
       $d="pages/";
       if(isset($_GET['p'])){
           $p=strtolower($_GET['p']);
        if(preg_match("/^[a-z0-9\-]+$/",$p) && file_exists($d.$p.".html")){
           include $d.$p.".html";
        }
         else{
           include $d."404.html";
            }
            }
       ?>
 </div>

And i use onpopstate (when my state is null load home.html, else load the history pages) to simulate an history. The problem is when my page statut is state = null (the first page load) my page is loading two time because of the include, how can i fix it ? And this is my ajax:

var afficher = function ( data, page ) {
    $( '#container' ).delay ( 300 ).fadeOut ( 400, function () {
        $( '#container' ).empty (); 
        $( '#container' ).append ( data );
  $( '#container' ).fadeIn ( 500, function (){
        } );

    } );
};

var loadPage = function ( page, storeHistory ) {
    if ( typeof storeHistory === 'undefined' ) {
        var storeHistory = true;
    }
    
    $.ajax ( {
        url: 'pages/' + page,
        cache: false,
        success: function ( html ) {
            afficher ( html, page );
            if ( storeHistory === true ) {
                history.pushState ( { 'key': 'value', 'url': page }, '', page );
            }
        },
        error: function ( XMLHttpRequest, textStatus, errorThrown ) {
            afficher ( 'erreur lors du chagement de la page' );
        }
    } );
    
    return false;
};

window.onpopstate = function ( e ) {
    if ( e.state === null ) {
        loadPage ( 'home.html' );
    } else {
        loadPage ( e [ 'state' ] [ 'url' ], false );
    }
};

$( document ).ready ( function () {
    $( '#menu a' ).on ( 'click',function ( e ) {
        var page = $( this ).attr ( 'href' );
        loadPage ( page );
        return false;
    } );
    
    $( '#container' ).on ( 'click', '.vs-transform a', function () {
        var page = $( this ).attr ( 'href' );
        loadPage ( page );
        return false;
    } );
} );
Thibaud
  • 396
  • 5
  • 23

1 Answers1

1

Page load is seen by some browsers as a popstate event. You need to defer binding the popstate event until after page load:

window.addEventListener('load', function() {
    setTimeout(function() {
        window.addEventListener('popstate', function() {
            //do stuff
        });
    }, 0);
});

See here

Community
  • 1
  • 1
sideroxylon
  • 4,338
  • 1
  • 22
  • 40