Question

I'm doing some tests with jQuery Mobile and trying to figure out how to setup an application and its various pages. Ideally, I would like the framework to load the pages with transitions but still keep each pages clearly separated. In particular, it seems that a page loaded via Ajax doesn't "clear" the JavaScript or CSS of the previous page:

Example 1 - JavaScript

For instance, if I have something like this in page1.html:

<script>
    setInterval(function() {
        console.info('Interval' + (new Date()));
    }, 1000);
</script>

Then if I load page2.html, the interval is still running. If I go back to page1, a new interval is started so there are now two intervals running, and 3 and 4, etc. every time I go back to page1.

Example 2 - CSS

Another issue is with styling. Let's say two developers, working independently on two different pages, create an element my-element. In page1, this element is styled:

<style>
    #my-element {
        color: red;
    }
</style>

<span id="my-element">This one is red</span>

in page2, the element is not styled:

<span id="my-element">This one has no style</span>

Again, if I go to page1.html first and then page2.html, my-element ends up being red, even though it wasn't styled in page2.html.

So I guess I have two questions:

  1. Currently it seems that jQuery Mobile approach to loading pages is not scalable at all. CSS, JS created on one page, carry on to the next. So is there any way to make jQuery Mobile load pages "cleanly". i.e. completely deleting everything from the previous page so that bits of JS or CSS don't affect the next page?

  2. If not, what is the correct way to work with multiple pages, in a scalable way, in jQuery Mobile?

Was it helpful?

Solution

the behavior you are describing is what makes JQM work. your DOM persists (including js and css of the first page you load), until you load a page using 'data-ajax=false' or 'rel=external' which will do a regular page load (no ajax).

By loading the page via ajax you will mostly have at least two pages in the DOM - the page you started on (like an anchor page) and any other page you are loading via ajax (which gets removed once the next page is loaded). 

this approach allows to have transitions and other functions which you can share across pages.

still you can easily target specific pages with js/css. I'm always runnimg a controller.js file in my applications, which handles page specific things by binding to any of the JQM events (pagebeforeshow, pageshow...). Likewise for page specific css, just use the page id attribute to make css page specific.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top