I know when you are switching pages around with jquery mobile using ajax it only grabs the DOM in the body with data-role="page"
. The problem is this is a phonegap app running on a mobile device so doing full page loads without ajax is pretty slow getting all the JS, CSS scripts.
I've been searching around trying different things. The docs say you can append javascript to the dom and put it under a data-role="page"
element but I still can't get it to fire this way.
What I am currently trying to is have a bootstrap script that is included at the top of the first page and on pagechange it tries to insert the js specific to that page in the dom
function insertScript(script, container) {
var elem = document.createElement('script');
elem.type = 'text/javascript';
elem.src = 'Assets/Scripts/' + script + '.js';
container.appendChild(elem);
}
$(document).bind('pagechange', function(event){
//get the path to the html asset
var path = document.location.pathname;
//split up
var arr = path.split('/');
//get the relevant part of the path ie index.html
var page = arr[arr.length-1];
// grab a list of all the divs's found in the page that have the attribute "role" with a value of "page"
var pages = $('div[data-role="page"]'),
// the current page is always the last div in the Array, so we store it in a variable
currentPage = pages[pages.length-1];
//if the page is index add index.js to the last dom node
if (page == 'index.html') {
insertScript('index', currentPage);
}
});
Then for example index.js has the following
$("#start_page").live('pageinit', function() {
alert('on start page');
});
but the pageinit function never fires. Any ideas
**edit:
I have multiple html pages, using index.html and home.html for example
*index.html
<html>
<head>
<script type="text/javascript" src="js/phonegap-1.3.0.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.0.min.js"></script>
<script type="text/javascript">
$("#index_page").live('pageinit', function() {
//do some page specific js functions for index.html
});
</head>
<body>
<div data-role="page" id="index_page">
<a href='home.html'>go to home page</a>
</div>
</body>
</html>
**home.html
<html>
<head>
<script type="text/javascript">
$("#home_page").live('pageinit', function() {
//this is the JS I want to pull
});
</head>
<body>
<div data-role="page" id="home_page">
<h1>this is the home page</h1>
</div>
</body>
</html>
So what will happen when I click on the link from index to home the dom gets updated but any JS on the home.html page WILL NOT be inserted into the page via AJAX so I'm trying to figure out a way to do that.
I know I could include ALL of my js in one page but I'm really trying to avoid that because I have alot of pages and it will get messy fast.