Adding inline javascript to script tag
Possible duplicate:
How do I add a JavaScript line (not an exteral.js file)?
I am trying to create a script tag dynamically. I want to add inline javascript to a script tag.
My code
var script = document.createElement("script")
script.type = "text/javascript";
var scriptContents = 'var isActive; window.onfocus = function () { isActive = true; }; window.onblur = function () { isActive = false; };';
var textNode = document.createTextNode(scriptContents);
script.appendChild(textNode);
document.getElementsByTagName("head")[0].appendChild(script);
The reason I want to do this is to determine if the browser tab is active or not.
My error code
SCRIPT65535: Unexpected method or property access call.
in line
script.appendChild(textNode);
thanks for the help
+3
source to share
1 answer
The Java script will be evaluated (compiled by the web browser) once after the page has loaded. an inline script function generated on the fly will not be recognized by the browser.
to create the script body you can use .src
var script = document.createElement("script").src = scriptContents;
OR..
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "//anycdn.com/api/lib.js"; //url to script CDN
-2
source to share