The coding below help you to create and insert new javascript function into a loaded html page. Which is very useful for dynamic external js libs binding. I personally recommend the first way:
function addFunc()
{
var sFunc = ""
+"function myOnUnLoad()"
+"{"
+"alert('unload...');"
+"};"
+"window.document.body.onunload = myOnUnLoad;";
window.eval(sFunc);
}
Second way, by this way you have to write down all your code in a external js file, in this case, let us say myjs.js file:
{
var sFunc = ""
+"function myOnUnLoad()"
+"{"
+"alert('unload...');"
+"};"
+"window.document.body.onunload = myOnUnLoad;";
window.eval(sFunc);
}
function addFunc()
{
var o = window.document.createElement("script");
o.type="text/javascript";
o.src="myjs.js";
//if you use o.innerHTML="..." or o.innerText="..." here, you will get a
//runtime error. That is why you have to use a external js file, and use
//o.scr="myjs.js" to insert function code
window.document.getElementsByTagName("head")[0].appendChild(o);
}
//-- code in myjs.js file
window.document.body.onunload = function ()
{
alert("unload...");
}
{
var o = window.document.createElement("script");
o.type="text/javascript";
o.src="myjs.js";
//if you use o.innerHTML="..." or o.innerText="..." here, you will get a
//runtime error. That is why you have to use a external js file, and use
//o.scr="myjs.js" to insert function code
window.document.getElementsByTagName("head")[0].appendChild(o);
}
//-- code in myjs.js file
window.document.body.onunload = function ()
{
alert("unload...");
}
No comments:
Post a Comment