1
$(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?

Chan
  • 1,947
  • 6
  • 25
  • 37

1 Answers1

1

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.

Miro
  • 8,402
  • 3
  • 34
  • 72
  • I would like to ask you one more question, will script keep occupied memory when I change to other page content? – Chan Mar 02 '15 at 04:32
  • I don't think it will. Once the elements are removed from the DOM, the javascript events will be released. Take a look [here](http://stackoverflow.com/questions/12528049/if-a-dom-element-is-removed-are-its-listeners-also-removed-from-memory). – Miro Mar 02 '15 at 05:19