Monday, June 11, 2012

Loading Scripts Dynamically In Jquery Mobile

At first, I loaded all of my scripts in the header (even when the scripts weren't needed when the page was being loaded).

I found this website that partially explained how to load scripts when the page loads. However, Jquery Mobile needs to use the delegate function to load the script when a page is showing.

I copied the function from the website above:
function loadjscssfile(filename, filetype){
 if (filetype=="js"){ //if filename is a external JavaScript file
  var fileref=document.createElement('script')
  fileref.setAttribute("type","text/javascript")
  fileref.setAttribute("src", filename)
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  var fileref=document.createElement("link")
  fileref.setAttribute("rel", "stylesheet")
  fileref.setAttribute("type", "text/css")
  fileref.setAttribute("href", filename)
 }
 if (typeof fileref!="undefined")
  document.getElementsByTagName("head")[0].appendChild(fileref)
}
Now, you need to add code to the top of the data-role="page" where you want the script to load:
$(document).delegate('#page', 'pageshow', function() {
 loadjscssfile("your.css", "css")
 loadjscssfile("your.js", "js")
});

No comments:

Post a Comment