Jquery Mobile - $.mobile.changepage not loading external .JS files

So I am having a hard time getting $.mobile.changePage to function properly. I call it like this:

$.mobile.changePage( "DataformsM-AddRecord.html", { transition: "slide"} );

But for some reason, when the HTML page is loaded, none of the external .js (the files that I wrote to actually do something) are included. I am following the significant loading conventions of

-Jquery
-(CUSTOM JS)
-Jquery Mobile

Does anyone know why this is not getting loaded properly? Also, the pageshow function is not getting fired either, which is strange. It looks like this:

$("div[data-role*='page']").live('pageshow', function(event, ui) { 

    loadFormFields();

});

Now the page is rendered, but none of the functional things happen. If I hack it and do something like this:

document.location.href="DataformsM-AddRecord.html";

It will function properly.


Solution 1:

jQuery Mobile does not pull the whole page into the dom, it grabs the first data-role="page" element and its descendants and pulls that into the current dom.

So any scripts in the <head> of the document will not be included.

I generally put all the functional JavaScript for my site on the index page and then when external pages are loaded into the dom they can benefit from the already loaded scripts.

Also, you can place JavaScript code inside the data-role="page" element and it will be included when jQuery Mobile does its AJAX load of the page.

UPDATE

A good system for this is to put all of your JS into an include file and include it on each page of the site. It will be ignored if pages are brought into the DOM by AJAX, but if someone refreshes somewhere in your site, the JS will be available.

Solution 2:

So building off of what Jasper so wisely noted above, I came up with a working solution.

Basically I Load up all of my JS and CSS files into the index page to start. Now when you load, this method will be triggered for the pageshow

$("div[id*='page1']").live('pageshow', function(event, ui) { 
    setTimeout(function() { window.scrollTo(0, 1) }, 100);
    doStuffWhenPageintializes();
});

Once I call the $.mobile.changePage( "someOtherPage.html", { transition: "slide"} );, the pagehide method will get fired for the page1 object. This is where you can trigger the method to initialize the page you are transitioning to.

$("div[id*='page1']").live('pagehide', function(event, ui) { 
    setTimeout(function() { window.scrollTo(0, 1) }, 100);
    loadStuffForNewPage();
});

Now you can remove the document.location.href="external.html" line and simply use the native JQM call. Hope this helps some people.

Solution 3:

Kindly repeat the head section with all the scripts in each html page, since change page will cause reload of pages and will re create head section...

a simple change page like this would then work:

$.mobile.changePage('abc.html', {
    transition: 'slide'
});