Last active
August 29, 2015 14:05
-
-
Save joseluisq/60935b0ba776827f0869 to your computer and use it in GitHub Desktop.
How to load only the body content from some static html page via Javascript Ajax.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// main.js | |
(function($){ | |
/** | |
For example: | |
You might load pages for each links on your menu. | |
Eg. | |
<ul> | |
<li><a href="#about">About</a></li> | |
<li><a href="#services">Services</a></li> | |
<li><a href="#contact">Contact</a></li> | |
</ul> | |
**/ | |
var url; | |
$('#mymenu a').click(function(e){ | |
// Prevent the open link | |
e.preventDefault(); | |
// Retrieve the link value and replace hash mark | |
url = $(this).attr('href').replace('#', ''); | |
// Sets the correct page | |
load_page( url + '.html' ); | |
}); | |
// The body content logic. | |
function body_content_logic() { | |
// Here your stuff for body content loaded data. | |
} | |
// Load some body content on any page. | |
function load_page(url) { | |
$.ajax({ | |
url: url, | |
dataType: 'text', | |
type: 'get', | |
success: function(str,b,xhr){ | |
// Retrieve the title text (if you want) | |
var title = str.match(/<(title)>[\s\S]*?<\/\1>/gi)[0].replace('<title>', '').replace('</title>', ''); | |
// Retrieve the body content | |
str = str.match(/<(body)>[\s\S]*?<\/\1>/gi); | |
str = str[0].replace('<body>','').replace('</body>', ''); | |
// Pay attention here: | |
// All code here in this example is saved in my case at "main.js" path. | |
// So, you need remove this script (or scripts) from your page "before" you embed the body content | |
// for avoid duplicity code on the fly. | |
str = str.replace('<script src="main.js"></script>', ''); | |
// Ok, now replace html body content on the current page. | |
$('body').empty().html(str); | |
// Change history page url (if you want) | |
window.history.pushState({}, title, url); | |
// Change the page's title (if you want) | |
document.title = title; | |
// Finally, call the method again for repeat the cycle | |
body_content_logic(); | |
} | |
}); | |
} | |
// Apply your logic for current body content | |
body_content_logic(); | |
}(jQuery)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment