igor-alexandrov / wiselinks

If Turbolinks are not enough for you. Wiselinks makes your application work faster.
MIT License
723 stars 89 forks source link

document.ready event is not triggered by wiselinks #41

Closed waiting-for-dev closed 11 years ago

waiting-for-dev commented 11 years ago

According to wiselinks README file:

While using Wiselinks you can rely on DOMContentLoaded or jQuery.ready() to trigger your JavaScript code [...]

But I don't see how. When I write some code for the document.ready event, it is not triggered again when wiselinks perform some request.

I have prepared a very simply Rails 3 application to demonstrate it and to show a minimalistic code that reproduces it.

The code of the application is in:

https://github.com/cram1010/wiselinks_bug

and an online demo in:

http://wiselinks-bug.herokuapp.com/

There is a simply alert("I'm an alert") line of code to be executed with the document.ready event. As you can see, the alert only appears with the pure-server requests, but not with the ones handled with wiselinks.

Am I doing something wrong or is it a bug?

billychan commented 11 years ago

This is not Wiselinks' bug.

The document is already ready after your first loading of page. When you click a Wiselinks link, Wiselinks load content from server to replace target div and change pushState, that's all. Except the changed div, the other parts of DOM are still there, still ready, nothing changed.

So the events already been fired at document ready won't be fired again. That's expected behaviour.

However your concern can be solved by utilizing Wiselinks' page:always event. The basic is

  1. Wrap the needed code in a function.
  2. Call this function at document ready.
  3. Call this function again at page:always.

Example code

$(document).ready ->
  page_init()

   $(document).off('page:always').on(
       'page:always'
       (event, xhr, settings) ->
         page_init()
   )

page_init = ->
   alert("test!")
   # and others
igor-alexandrov commented 11 years ago

@billychan is absolutely right here. Another common pattern that can be used is to add some JS code (maybe some class initialization to document.ready in HTML that is loaded with Wiselinks (this is done in Wiselinks example application on proposals page).

waiting-for-dev commented 11 years ago

Ok, this makes sense... Following paragraph fragment in the README is the one that confused me:

While using Wiselinks you can rely on DOMContentLoaded or jQuery.ready() to trigger your JavaScript code, [...]

Thanks!