So this is our scenario... First thing we do is, we append a piece of javascript code which adds external script to document like this:
(function() {
var e = document.createElement('script'); e.type = 'text/javascript'; e.async = true; e.src = 'http://blabla.com/script.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(e, s);
})();
Then in script.js following happens:
function ajaxCall() {
//... some script to send ajax request which calls createDiv() after success
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
createDiv(xmlhttp.responseText);
}
};
xmlhttp.open("GET","http://blabla.com/api/");
xmlhttp.send();
}
function parseResponse(response) {
var parser = new DOMParser();
var dom = parser.parseFromString(response, "text/html");
return dom;
}
function createDiv(responsetext)
{
var dom = parseResponse(responsetext);
var _ws = dom.getElementById('styles');
var h = document.getElementsByTagName('head')[0];
h.appendChild(document.importNode(_ws, true));
var _jr = dom.getElementById('script1').outerHTML;
var _vc = dom.getElementById('script2').outerHTML;
var _rv = dom.getElementById('script3').outerHTML;
var _rw = dom.getElementById('my_div');
var _b = document.getElementsByTagName('body')[0];
var _d = document.createElement('div'); _d.id = 'just_id';
_d.innerHTML = _jr + _vc + _rv;
_d.appendChild(document.importNode(_rw, true));
_b.appendChild(_d);
}
ajaxCall();
Everything works fine, script's and a div are being appended as expected and where expected, but appended script doesn't get executed and doesn't affect appended div. Why is that? And how can I make it execute? We also don't get any warnings/errors in console. Using latest firefox.
EDIT 1
Comment: The example script you showed just defines function, but it never actually calls them
It actually calls a function which makes an ajax request, please check edited code snippet.
EDIT 2
Comment: Have you tried to put the logic in a callback and then call it in createDiv? May be add some logs to test if its getting called but it unable to find div
I just tried console.log('hello world'); call in one of scripts which are being appended by createDiv() function, but it does nothing.
EDIT 3
For more details. When page is loaded, I can see
<script type="text/javascript" id="script1" src="http://blabla.com/script1.js"></script>
<script type="text/javascript" id="script2" src="http://blabla.com/script2.js"></script>
<script type="text/javascript" id="script3" src="http://blabla.com/script3.js"></script>
<div id="just_id">Content here</div>
In DOM-Inspector and as mentioned above, there is console.log('hello world'); to test it, but it doesnt get executed.
EDIT 4
Added some CSS through createDiv() function to document's <head></head> and it affects my div with id 'just_id'. JS still isn't working.
EDIT 5
Also tried to append inline javascript instead of external one in my function, but still no success. Can see following in DOM-Inspector, but code doesn't log anything.
<script type="text/javascript">
console.log('test');
</script>
EDIT 6
I also tried to import nodes from as suggested here
This method is not allowed to move nodes between different documents. If you want to append node from a different document the document.importNode() method must be used.
and also tried to changed order. 1.css 2.div 3.js like this but still no success... Anyone has an idea what is going on here?
Check the code above
EDIT 7
As suggested in How do you execute a dynamically loaded JavaScript block? I set innerHTML of my div to scripts + content and then appended to DOM like this:
Check the code above
But still without any success.
EDIT 8
Added ajax function code. 3rd paramter in xmlhttp.open("GET","http://blabla.com/api/"); true (asynchronous) and false (synchronous) already tried. Still no success.
EDIT 9
function createDiv() as suggested in answer:
var dom = parseResponse(responsetext);
var _jr = dom.getElementById('script1'); //<script> tag with src attribute
var _vc = dom.getElementById('script2'); //inline <script> for test purposes only, it should actualy be external script also
var _rv = dom.getElementById('script3'); //inline <script>
var _rw = dom.getElementById('external_div');
var _b = document.getElementsByTagName('body')[0];
var _d = document.createElement('div'); _d.id = 'internal_div';
_d.appendChild(document.importNode(_rw, true));
_d.appendChild(document.importNode(_jr, true));
_d.appendChild(document.importNode(_rv, true)); //without second parameter TRUE, I dont get script content
_d.appendChild(document.importNode(_vc, true)); //without second parameter TRUE, I dont get script content
_b.appendChild(_d);
Doesn't work. Work's only if I take innerHTML of inline scripts from other document, create elements like suggested in answer, set their innerHTML and then append do current document. External script's wont load at all.
EDIT 10
.htaccess from localhost... :
<Files *.html>
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Files>
<Files *.php>
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Files>
<Files index.php>
Order Allow,Deny
Allow from all
</Files>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /page1/
#RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>
.htaccess from 192.*** ... :
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /direktexpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /page2/index.php [L]
</IfModule>
# END WordPress
EDIT 11
So I am probably going to give bounty #Drakes, just for the effort and his spent time on my question and going to show some screenshots what is going on. It is definitely firefox bug, I just tested on chrome and it works.
1st picture: source code of 192.168.2.197/testing/whatever/etc. .htaccess remains the same as in example above
2nd picture is source code for script.js, which is being loaded on 192.168.2.197/testing/whatever/etc. .htaccess remains the same as in example above:
3rd picture is a screenshot of inspector, how does my dom look like:
4th picture.... nothing happens. Just a warning which has nothing to do with my problem (I hope so), because even when I remove all scripts, it still appears.
Is it a firefox bug?
The problem is that the code above is mixing appendChild with innerHTML. It's not intuitively obvious that the two perform differently in some cases. The former allows newly inserted script nodes to be executed as they are attached to the DOM. The latter doesn't. This has been a head-scratcher for many people. Kindly Google "script and innerHTML" and you will find that you are not alone facing this similar problem.
If you (1) change
_d.innerHTML = _jr + _vc + _rv
to
_d.appendChild(document.importNode(_jr));
_d.appendChild(document.importNode(_vc));
_d.appendChild(document.importNode(_rv));
and additionally (2) change
var _jr = dom.getElementById('script1').outerHTML;
var _vc = dom.getElementById('script2').outerHTML;
var _rv = dom.getElementById('script3').outerHTML;
to
var _jr = dom.getElementById('script1');
var _vc = dom.getElementById('script2');
var _rv = dom.getElementById('script3');
then your scripts will get executed. Here is a demonstration:
var b = document.getElementsByTagName('body')[0];
/* Works */
var s1 = document.createElement('script');
s1.innerHTML = "console.log('I will execute')";
b.appendChild(s1);
/* Fails */
var s2 = document.createElement('script');
s2.innerHTML = "while(1){alert('Do not worry! I will not execute');}";
b.innerHTML = s2.outerHTML;
console.log("It didn't execute");
Tested
I ran the OP's code on my server to replicate the problem as best I can. Given the supplied code I can make it work as intended on my server. I only changed the AJAX URL from http://blabla.com/api/ to api.html and supplied my own file as none was provided by the OP, but I pieced together what it should contain from the OP's JavaScript). Here are sample results:
index.html
<html lang="en">
<body>
<script>
(function() {
var e = document.createElement('script'); e.type = 'text/javascript'; e.async = true; e.src = 'script.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(e, s);
})();
</script>
</body>
</html>
script.js
This is the OP's code modified to my specifications above (using appendChild instead of innerHTML, and the AJAX call returns the contents of api.html below)
function ajaxCall() {
//... some script to send ajax request which calls createDiv() after success
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
createDiv(xmlhttp.responseText);
}
};
xmlhttp.open("GET","api.html");
xmlhttp.send();
}
function parseResponse(response) {
var parser = new DOMParser();
var dom = parser.parseFromString(response, "text/html");
return dom;
}
function createDiv(responsetext)
{
var dom = parseResponse(responsetext);
var _ws = dom.getElementById('styles');
var h = document.getElementsByTagName('head')[0];
h.appendChild(document.importNode(_ws, true));
var _jr = dom.getElementById('script1');
var _vc = dom.getElementById('script2');
var _rv = dom.getElementById('script3');
var _rw = dom.getElementById('my_div');
var _b = document.getElementsByTagName('body')[0];
var _d = document.createElement('div'); _d.id = 'just_id';
_d.appendChild(document.importNode(_jr, true));
_d.appendChild(document.importNode(_vc, true));
_d.appendChild(document.importNode(_rv, true));
_d.appendChild(document.importNode(_rw, true));
_b.appendChild(_d);
}
ajaxCall();
api.html (returned by the AJAX call)
<!DOCTYPE html>
<html>
<body>
<style type="text/css" id="styles"></style>
<script type="text/javascript" id="script1" src="script1.js"></script>
<script type="text/javascript" id="script2">console.log("incline script 2")</script>
<script type="text/javascript" id="script3">console.log("incline script 3")</script>
<div id="my_div"></div>
</body>
</html>
script1.js
console.log("src script1");
Here are the DevTools results to show this is working.
The JavaScript of the page has already been parsed, you need to eval the result to put it into the window context.
function evalRequest(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
eval(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
};
UPDATE : you might need to get the script as text and then eval it )
function getScriptsAsText() {
var div = document.createElement('div');
var scripts = [];
var scriptNodes = document.getElementsByTagName('script');
for (var i = 0, iLen = scriptNodes.length; i < iLen; i++) {
div.appendChild(scriptNodes[i].cloneNode(true));
scripts.push(div.innerHTML);
div.removeChild(div.firstChild);
}
return scripts;
};
The problem is your method is asynchronous not synchronous execution. Meaning the page is still loading while you insert your dynamical scripts.
There are few ways to do so:
The easiest way is to use jQuery $(document).append instead of
document.createElement, if you don't mind using the library.
You can also use jQuery $.getScript.
If you prefer not to include 3rd libraries, you have to think of a way to delay page load while you insert your scripts, something like an alert to creat a prompt window will work, but user experience not so good, think of a more smooth way.
Use XMLHTTPRequest to retrieve your scripts. This is synchronous and I can see you are familiar with it because you are using it in your script already.
Good luck and happy coding.
Have you tried getting the URL of the src file and excuting it with jQuery's getScript() function?
Change your creatediv() function :
var _jr = dom.getElementById('script1').outerHTML;
var srcScript1Left = _jr.split('src="');
srcScript1Right = srcScript1Left[1].split('"');
srcScript1 = srcScript1Right[0];
console.log(srcScript1);
$.getScript(srcScript1, function()
{
// The external script has been executed.
});
EDIT
Similar method in pure Javascript :
var _jr = dom.getElementById('script1').outerHTML;
var srcScript1Left = _jr.split('src="');
srcScript1Right = srcScript1Left[1].split('"');
srcScript1 = srcScript1Right[0];
console.log(srcScript1); // Display the name of the external script file
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
eval(xmlhttp.responseText); // Execute the external script
}
};
xmlhttp.open("GET",srcScript1);
xmlhttp.send();
You are currently loading a script into your page. This happens AFTER the page js was already executed (since is async and usually loading an external resource takes longer than the script execution).
So... basically you have the right function definitions and everything, and calling them from console later should work (I think you already tried that and was fine).
Still, the calls to your functions, even thought they are there won't execute since will not be computed after load.
To work around this, you can create an ajax request to a page that has the script, and in its callback to call whatever function you need to call.
I would say remove async, as the action comes after the initial page load
(function () {
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(CreateScriptTag('http://blabla.com/script.js',true), s);
})();
function CreateScriptTag(src, isAsync) {
var e = document.createElement('script')
e.type = 'text/javascript';
e.async = isAsync;
e.src = src;
return e;
}
function ajaxCall() {
//... some script to send ajax request which calls createDiv() after success
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", "http://blabla.com/api/");
xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) createDiv(xmlhttp.responseText); };
xmlhttp.send();
}
function parseResponse(response) {
var parser = new DOMParser();
var dom = parser.parseFromString(response, "text/html");
return dom;
}
function createDiv(responsetext) {
var head=document.getElementsByTagName('head')[0],dom = parseResponse(responsetext),_div=document.createElement('div');
head.appendChild(document.importNode(dom.getElementById('styles'), true)); //Assuming stylesheets are working fine.
_div.id = 'just_id';
//div.innerHTML = _script1 + _script2 + _script3;
document.getElementsByTagName('body')[0].appendChild(_div.appendChild(dom.getElementById('my_div')));
head.appendChild(CreateScriptTag(dom.getElementById('script1').getAttribute("src"),true));
head.appendChild(CreateScriptTag(dom.getElementById('script2').getAttribute("src"),true));
head.appendChild(CreateScriptTag(dom.getElementById('script3').getAttribute("src"),true));
/* or another idea;
document.write(_script1 + _script2 + _script3);
*/
}
ajaxCall();
Related
Looking for advise on whether is it possible to have a footer.html and duplicate it to all pages without using PHP.
I know I can use include("footer.php"), but all my pages are in HTML now and I will have to change all css paths.
I read up w3school on how to use w3-include-html & javascript. However I realize the javascript is lagging every pages, making page loading longer.
Is there any other option?
<body>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
return;
}
}
}
</script>
<div w3-include-html="footer.html"></div>
<script>
includeHTML();
</script>
You could think different, but I don't know if it is, what you want, because the architecture of your application will grow up / become a littlebit ugly.
You define a php-script, that is loading your static html and appends the php-code you want. Then you need a rewrite rule, to get the script as the center of your tiny html-universe ;-)
An example, that should work on an apache with rewrite-mod enabled.
Mention, that you create this directory-structure on your server:
.../.htaccess
.../index.php <<< this renders the "header", content of your html-files and last footer
.../html-pages <<< place your files here
Place an .htaccess in the root-folder:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond "%{REQUEST_URI}" !^.*/index\.php$
RewriteRule ^(?!.*index\.php)(.*)$ /index.php/$1 [QSA,L]
Place an index.php in the samefolder:
<?php
... here could be your header-code
define ('PAGES_DIR', __DIR__ . '/html-pages')
define ('DEFAULT_PAGE', 'index.html')
// we need to handle virtual pathes
$requestPath = false;
if (isset($_SERVER['PATH_INFO'])) {
$requestPath = $_SERVER['PATH_INFO'];
} elseif (isset($_SERVER['ORIG_PATH_INFO']) && strpos($_SERVER['ORIG_PATH_INFO'], basename(__FILE__)) === FALSE) {
$requestPath = $_SERVER['ORIG_PATH_INFO'];
}
if ($requestPath == '/' || strlen(trim($requestPath)) == 0 || strlen(trim($requestPath)) == basename(__FILE__)) {
$requestPath = DEFAULT_PAGE;
}
// this sends the content of your file to the browser
#readfile(PAGES_DIR . "/$requestPath");
... now your footer-code
And your html-files needs be placed into the "html-pages"-folder.
If you have done, your server should handle http://domain.tld/bla-fasel-blub.html as followed:
redirect the not existing path to index.php
RewriteRule ^(?!.index.php)(.)$ /index.php/$1 [QSA,L]
render the header
read the requested html-file (the $1 of the RewriteRule will be "bla-fasel-blub.html" and becomes value of "$requestPath") and send the content to the browser
render the rest of index.php (the footer or whatever)
I hope it helps, generating an idea for your problem.
My problem is that I have a JavaScript function written in a PHP file and when I call it from AJAX request, I want to run that JavaScript function on the main page too after successful AJAX request. As an example, I have a main.html file where I have written an AJAXX function as below.
main.html
<script type="text/javascript">
/* AJAX Function
----------------------------------------------- */
function ajaxFunction() {
var FD = new FormData();
var ajx = new XMLHttpRequest();
ajx.onreadystatechange = function () {
if (ajx.readyState == 4 && ajx.status == 200) {
document.getElementById("mainContent").innerHTML = ajx.responseText;
hello(); //Uncaught ReferenceError: hello is not defined
}
};
ajx.open("POST", "/example.php", true);
ajx.send(FD);
document.getElementById("mainContent").innerHTML = 'Loading...';
return false;
}
</script>
And my example.php file contains a JavaScript function as
example.php
<?php
echo 'Some contents and functions';
echo '<script type="text/javascript">
function hello() {
alert("Hello");
}
</script>';
echo 'Some contents and functions';
?>
Now when I run index.html file, I get Uncaught ReferenceError: hello is not defined error in console rest I am seeing the function body is written on HTML page while inspecting elements on-page.
As I know that innerHTML does not run scripts. So what's the workaround to this problem. You can view the below-linked answer also that I think is related to my question but tried and not working with my problem.
Researched Questions/Answers:
https://stackoverflow.com/a/3250386/3170029
https://stackoverflow.com/a/47614491/3170029
As I shared and you know that innerHTML does not run scripts. so we have to look around it then I found a solution on StackOverflow and I am sharing here with this problem's answer.
main.html
<script type="text/javascript">
/* AJAX Function
----------------------------------------------- */
function ajaxFunction() {
var FD = new FormData();
var ajx = new XMLHttpRequest();
ajx.onreadystatechange = function () {
if (ajx.readyState == 4 && ajx.status == 200) {
setInnerHTML(document.getElementById("mainContent"), ajx.responseText); // does run <script> tags in HTML
hello();
}
};
ajx.open("POST", "/example.php", true);
ajx.send(FD);
document.getElementById("mainContent").innerHTML = 'Loading...';
return false;
}
//https://stackoverflow.com/a/47614491/3170029
var setInnerHTML = function(elm, html) {
elm.innerHTML = html;
Array.from(elm.querySelectorAll("script")).forEach(oldScript => {
const newScript = document.createElement("script");
Array.from(oldScript.attributes)
.forEach(attr => newScript.setAttribute(attr.name, attr.value));
newScript.appendChild(document.createTextNode(oldScript.innerHTML));
oldScript.parentNode.replaceChild(newScript, oldScript);
});
}
</script>
Its concept is clear. When you get the response data from PHP file then first extract <script ..... </script> tags from it and add them in index.html file hear by using createElement('script') and copy all the script to this then you can easily call your function after response data anywhere.
In other words, You can create an executing script element outside of that initial parse using the DOM method of calling createElement('script'), setting its src/content, and adding it to the document. The alternative is what jQuery's getScript90 does.
I have a type of SPA which consumes an API in order to fetch data. There are some instance of this SPA and all of them use common style and script files. So my problem is when I change a single line in those files, I will have to open each and every instances and update the files. It's really time consuming for me.
One of the approaches is to put those files in a folder in the server, then change the version based on the time, but I will lose browser cache if I use this solution:
<link href="myserver.co/static/main.css?ver=1892471298" rel="stylesheet" />
<script src="myserver.co/static/script.js?ver=1892471298"></script>
The ver value is produced based on time and I cannot use browser cache. I need a solution to update these files from the API, then all of the SPAs will be updated.
In your head tag, you can add the code below:
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:4000/getLatestVersion"; //api path to get the latest version
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var tags = JSON.parse(xmlhttp.responseText);
for (var i = 0; i < tags.length; i++) {
var tag = document.createElement(tags[i].tag);
if (tags[i].tag === 'link') {
tag.rel = tags[i].rel;
tag.href = tags[i].url;
} else {
tag.src = tags[i].url;
}
document.head.appendChild(tag);
}
}
};
xmlhttp.open("POST", url, false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
</script>
Your api path should allow "CORS" from your website that handles the code above.
And your api should return a json data like below:
var latestVersion = '1892471298'; //this can be stored in the database
var jsonData = [
{
tag: 'link',
rel: 'stylesheet',
url: 'http://myserver.co/static/main.css?ver=' + latestVersion
},
{
tag: 'script',
rel: '',
url: 'http://myserver.co/static/script.js?ver=' + latestVersion
}
];
//return jsonData to the client here
If you change anything in your JS or CSS then you have to update the browser cache, all you can do is to update that particular JS version not all of them, it should reflect in browser.
How about adding a method in your API returning the files' last modified time and then inserting the value into the "src"/"href" attribute after the "ver="
I made an html website that will be running in a CD-R (this will be a manual).
I have the page created and everything is working good, but at this moment I'm having some problems for opening a XML file.
My question is, is this possible, since It will be running in a CD Drive?
Thank you
This is what I have:
function testing()
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "teste.txt", true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
var allText = rawFile.responseText;
alert(allText);
}
else
alert("erro no xml");
}
rawFile.send();
}
This works fine in for example: localhost/path
But i want it to work in a path like c:\path\
If you don't mind modifying your source files a little bit by turning it into JSON, you could use JSONP. Here's a simple example:
<button onclick="go();">Click me</button>
<script type="text/javascript">
function go() {
var scriptTag = document.createElement("script");
scriptTag.src = "someText.js";
document.getElementsByTagName("body")[0].appendChild(scriptTag);
}
function jsonCallback(txt) {
console.log(txt);
}
</script>
File: someText.js:
jsonCallback("Hello World!");
I'd like to load/insert an external html page into my web page. Example :
<b>Hello this is my webpage</b>
You can see here an interresting information :
XXXX
Hope you enjoyed
the XXXX should be replaced by a small script (the smaller as possible) that load a page like http://www.mySite.com/myPageToInsert.html
I found the following code with jquery :
<script>$("#testLoad").load("http://www.mySite.com/myPageToInsert.html");</script>
<div id="testLoad"></div>
I would like the same without using an external javascript library as jquery...
There are 2 solutions for this (2 that I know at least):
Iframe -> this one is not so recommended
Send an ajax request to the desired page.
Here is a small script:
<script type="text/javascript">
function createRequestObject() {
var obj;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(req) {
var http = createRequestObject();
http.open('get', req);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if (http.readyState == 4) {
var response = http.responseText;
document.getElementById('setADivWithAnIDWhereYouWantIt').innerHTML=response;
}
}
sendReq('yourpage');
//previously </script> was not visible
</script>
Would an iframe fit the bill?
<b>Hello this is my webpage</b>
You can see here an interresting information :
<iframe id="extFrame" src="http://www.mySite.com/myPageToInsert.html"></iframe>
Hope you enjoyed
You can set the src attribute of your iframe element using plain old javascript to switch out the page for another
I think what you are looking for are in the Jquery source code.
you can see more details here $(document).ready equivalent without jQuery