1

I'm writing a software which has views such as calendar and customer search. For example the main page contains links to these subsections. When the user navigates to the calendar page, the events of today are loaded from the backend via AJAX query. When an individual event is opened from the calendar view, its details are again loaded from the backend dynamically.

The first prototype was written as one big HTML file with all the JavaScript code embedded directly. Now I've started to refactor this into a more manageable system.

The problem is that I would like to separate each view as its own page which could be used independently but also as part of jQuery Mobile site with smooth AJAX transitions. Based on my observations loading a page via AJAX link in jQuery Mobile means that from the target page only the element marked with data-role="page" attribute is injected into the source page's HTML. All the script tags are stripped.

How should I separate the views but still maintain the smooth AJAX transitions?

Ville Salonen
  • 2,654
  • 4
  • 29
  • 34

2 Answers2

1

This is the solution I have used. Include a JavaScript file ref in your initial index page. In this you have the following code which is called when the new pages are loaded.

$('div[data-role="page"]#page-id').live('pageshow', function(e){

    // put the code you want to execute when the page is loaded here

}

By using one JavaScript file for each page you can keep a clean project structure, but they have to all be referenced in the initial index page. You can replace pageshow with pagebeforecreate or pagecreate depending on when you want the script to run.

The alternative would be the load the files dynamically like this:

var newjs = document.createElement('script');
newjs.setAttribute("type","text/javascript");
newjs.setAttribute("src", "page-two.js");

But that wouldn't be very useful if you are using the JavaScript to alter the DOM, as that needs to be done before the page is shown.

Jivings
  • 22,834
  • 6
  • 60
  • 101
0

Related: AJAX Request Help for next/previous page

Live Demo: http://jsfiddle.net/Jaybles/MawSB/

Link to Answer: AJAX Request Help for next/previous page

If this help +1 to the linked answer above

Community
  • 1
  • 1
Phill Pafford
  • 83,471
  • 91
  • 263
  • 383
  • I don't think this answers the question. OP wants to know how to include the new pages JavaScript when it is in the header tags (which don't get loaded when the page is changed). – Jivings Jun 16 '11 at 08:49
  • 1
    @Jivings - And this include should not happen (and can't be done in any conventional way) in JQM, so it's nice to know how it can be done instead. – naugtur Jun 16 '11 at 10:55