Search code examples
jqueryajaxsmoothstate.js

Stop jQuery .html() loading javascript


I am using smoothState.js to prefetch a page through ajax. When it updates the page with the html it loads the javascript file again.

The page then seems to run both causing errors. Can I stop jQuery loading the script?

    /** Run when requested content is ready to be injected into the page  */
    onEnd : {
        duration: 0,
        render: function (url, $container, $content) {
            $body.css('cursor', 'auto');
            $body.find('a').css('cursor', 'auto');
            $container.html($content);
        }
    },

The script in the html that that it loads a second time after the ajax load

<script src="/js/main.min.js" async defer="defer"></script>

Solution

  • if i understand correctly, try this:

    var stop;
    
    
    /** Run when requested content is ready to be injected into the page  */
    onEnd : {
        duration: 0,
        render: function (url, $container, $content) {
            // the id #content must be after script tag in your page
            if(stop) $content = jQuery($content).find('#content').html(); 
            $body.css('cursor', 'auto');
            $body.find('a').css('cursor', 'auto');
            $container.html($content);
            // after first request enable stop variable
             stop = true;
        }
    },
    

    html:

    <script src="/js/main.min.js" async defer="defer"></script>
    
    <div id="content">.........</div>