1
votes

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?

2

2 Answers

1
votes

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.