Chan
Chan

Reputation: 1969

How to run javascript which file were loaded by pushState

$(function() {
    var content = $('#content');

    $('a').on('click', function(e) {
        History.pushState(null, $(this).text(), $(this).attr('href'));

        return false;
    });

    History.Adapter.bind(window, 'statechange', function() {
        var state = History.getState();

        content.html('loading...');

        $.get(state.url, function(response) {
            content.html($(response).filter('#content').html());
        });
    });
});

browserstate/history.js

I would like to use pushState to change page content, but actually each content might have different JavaScript to run, there are two ways on my mind to solve it

  1. write all possible functions in one script, use jQuery on to bind the event
  2. put JavaScript inside the #content, therefore, when render content will also render the script

First solution will make js file bigger and more complicated, second solution will cause html file ugly, any better solution?

Upvotes: 1

Views: 343

Answers (1)

Miro
Miro

Reputation: 8650

I've done the second option and it works well. Just keep in mind that the <script> tags will be stripped and added to the bottom.

You are actually ajax-ing the content using $.get

You can use .load() instead of .get(), .html() and .filter()

content.load( state.url+" #content" );

It's specifically designed for loading one elements's html into another.

Upvotes: 1

Related Questions