Let's consider this situation.
I have a folder called /jscript, inside which there are two files called my_js_file1.js and my_js_file2.js.
I've also a page, /index.html, like this:
<html>
<head>
<script type='text/javascript' src='jscript/my_js_file1.js'></script>
</head>
<body>
<iframe src=''/>
</body>
</html>
Now, let's assume that, via the my_js_file1.js, I want to add to the <head> tag of the iframe, the following tag:
<script type='text/javascript' src='my_js_file2.js'></script>
Is the above src correct? If yes, it means that the document inside the iframe refers to the "working directory" of the javascript file.
If the previous is not, does the following solution work?
<script type='text/javascript' src='jscript/my_js_file2.js'></script>
(Working of this last one means that the "working directory" is the same of the html file)
Regardless of the result, is there someone is able to explain the correct behaviour?
jscript/my_js_file2.js should be correct.
Documents and elements do have a so-called "base URI". It is used for resolving relative links such as yours.
The base URL of a document defaults to the document's address (as
displayed by the browser and available in window.location), but can
change from the default:
• When an HTML <base> tag is found in the document;
• When this is a new document created dynamically.
— Node.baseURI - Mozilla Developer Network (MDN)
Under the assumption that your HTML file does not contain any <base> tags, the base URI is /index.html.
You can prove this behavior by verifying the value of document.baseURI:
<!doctype html>
<html>
<head>
<script src="subdir/include.js"></script>
</head>
<body>
</body>
</html>
include.js:
alert(document.baseURI);
Related
i'd like to isolate the javascript code from the html code in two diferent files, originally I had this code:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p id="body">HTML Text</p>
</body>
</html>
<script>
$(document).ready(function () {
$("#body").text("JS Text");
});
</script>
and the output of the <-p-> was the expected "JS Text".
Then I tried to isolate the js script to another file (script.js):
window.onload = function(){
var text = document.getElementById('body');
text.innerHTML ='JS Text';
}
I've also make the reference at the html file:
<script type="text/javascript"src="scripts.js"></script>
but then the output text is no longer the expected (JS Text) but (HTML text)
what else do I need to make the js script work again?
First, it is invalid to place anything after the closing HTML tag, so while your first bit of code worked, it was invalid.
If you remove the JavaScript and place it in its own file, it will continue to work as long as you reference the file properly (use a relative reference and test the file on a web server) and place the script element just prior to the closing body tag so that when the script is processed and attempts to find the right DOM element, the DOM will have been loaded at that time.
FYI:
If you have JQuery in the referenced script file, then your
script that references JQuery will need to occur in the HTML prior
to the script that uses it.
The type attribute in the script tag has not been needed in
several years.
It's not a good idea to name anything body so that you won't cause
confusion with the body element.
Don't use .innerHTML when the string you are working with doesn't
contain any HTML. .innerHTML has security and performance
implications. Use .textContent instead.
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<p id="body">HTML Text</p>
<script src="relativePathToFile.js"></script>
</body>
</html>
I'm working through the 'create a platform game' project from Eloquent JavaScript and have an issue with script tags.
In the book we're told to display our level using:
<link rel="stylesheet" href="css/game.css">
<script>
var simpleLevel = new Level(simpleLevelPlan);
var display = new DOMDisplay(document.body, simpleLevel);
</script>
I've tried adding this (together with an additional script tag for my platform.js file) into index.html but the browser is giving nothing back, not sure what I'm doing wrong?
Ensure you are inserting your scripts in the right order:
<!DOCTYPE html>
<html>
<head>
Here you should put your "included" scripts with <script src=...>
</head>
<body>
...
</body>
<script>
Here you should put your first execution, if it needs the html page been completely loaded (as to use document.body).
</script>
</html>
The scripts are being executed as they appear into the page. If you use document, you have to delay the execution until the whole page has been loaded: Either by putting your script at the end of the HTML, either by putting an initialization function within the HEAD, and call it from body onload:
<head>
<script>
function myFunction(){...}
</script>
</head>
<body onload="return myFunction()">
...
</body>
Make sure to include the external JavaScript file you need in a separate <script> tag before your inline script!
I have a weird situation where I need to run a script inside of the <title></title> tags. I have no access to any of the others parts of the page, including the <head></head> tags. It has to be within the <title></title> tags (the reason is because we are dealing with an iframe response from a 3rd party server and we don't really have access to the full page.).
What I tried was:
<title>
<script type="javascript">
runMyFunction();
</script>
</title>
The problem is that it interprets the whole thing as a script. Is there anything I could do to tell the browser to run that code as a script and not treat it as a string?
You can't.
Per the HTML5 specification, the only permissible content of the <title> tag is plain text. Other tags, such as <script> tags, cannot be present in the context of a <title>.
<title>[trick</title>
<script type="javascript">
runMyFunction();
</script>
<title>:)]</title>
Everyting between the [] is what you should set as title. Most probably it won't work though, 'cause if I were them I would properly encode whatever string you send, in order not to let you do any tricks...
Can you just rewrite <title> later?
<head>
<title>My Title</title>
<script>
document.title = runMyFunction()
</script>
</head>
I want to get content of script tag example
now see above in src property load bolo7.com content i want to catch that contain
i have try so many method but it doesn't work
try 1 -> document.getElementById("data").innerHTML; //doesn't work
try2 -> document.getElementById("data").text; //doesn't work
if you are intelligent in javascript please give me answer that how to get content of script inside content
thanks in advance for your answer
my website is : http://www.bolo7.com/
The text property defined by the HTMLScriptElement interface is the text content of the script element. If the element uses a src attribute, it should not have any content so its text property will be an empty string.
In that case, you will need to access the src some other way, perhaps XMLHttpRequest will suit.
Note also that the id attribute for script elements is not valid for the DOCTYPE being used at the linked resource (and the document is invalid).
Something like this?
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
//some data here
function add1(x) {
return 1 + x;
}
</script>
<script type="text/javascript">
alert(document.getElementsByTagName("script")[0].innerHTML);
</script>
</head>
<body>
</body>
</html>
but RobG is right, only works for inline javascript.
I read that you should define your JavaScript functions in the <head> tag, but how does the location of the <script> (whether in the <head>, <body>, or any other tag) affect a JavaScript function.
Specifically, how does it affect the scope of the function and where you can call it from?
Telling people to add <SCRIPT> only in the head sounds like a reasonable thing to do, but as others have said there are many reasons why this isn't recommended or even practical - mainly speed and the way that HTML pages are generated dynamically.
This is what the HTML 4 spec says :
The SCRIPT element places a script
within a document. This element may
appear any number of times in the HEAD
or BODY of an HTML document.
And some sample HTML. Doesn't it look pretty all formatted here :)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A document with SCRIPT</TITLE>
<META http-equiv="Content-Script-Type" content="text/tcl">
<SCRIPT type="text/vbscript" src="http://someplace.com/progs/vbcalc">
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT type="text/javascript">
...some JavaScript...
</SCRIPT>
</BODY>
</HTML>
And something to look forward to in HTML 5 :
New async attribute in <SCRIPT> :
Note: There are ways [sic] a script can be
executed:
The async attribute is "true": The
script will be executed asynchrously
with the rest of the page, so the
script will be executed while the page
continues the parsing.
The async attribute is "false", but
the defer attribute is "true": The
script will be executed when the page
is finished with the parsing.
The normal rules of play still stand; don't use stuff before it's defined. :)
Also, take note that the 'put everything at the bottom' advice isn't the only rule in the book - in some cases it may not be feasible and in other cases it may make more sense to put the script elsewhere.
The main reason for putting a script at the bottom of a document is for performance, scripts, unlike other HTTP requests, do not load in parallel, meaning they'll slow down the loading of the rest of your page. Another reason for putting scripts at the bottom is so you don't have to use any 'DOM ready' functions. Since the script tag is below all elements the DOM will be ready for manipulation!
EDIT: Read this: http://developer.yahoo.com/performance/rules.html#js_bottom
One of the aspects of placement is performance. See this fine article within the YSlow discussion for why it's sometimes recommended you put them at the bottom of the document.
As for issues of scope, the usual visibility rules for Javascript (vars defined inside or outside of functions, local, global, closures, etc.) are not affected so far as I know.
Position of script tag does matter.
If you bind a Function with document Element then the document element has to be loaded first before we implement function. suppose getTeachers() is function in getTeachers.js file.
This will give you an error:
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Unit Teachers</title>
<head>
<script type="text/javascript" src="getTeachers.js"></script>
<script type="text/javascript">
document.getElementById("buttonId").onclick=function(){getResults()};
</script>
</head>
<body>
<form>
<input type = "button" id="buttonId" value = "Press for Results" /><br />
</form>
<span id="results" /></span>
</body>
</html>
It gives error before head is loaded first and it cannot find element with id specified.
The below code is correction:
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Unit Teachers</title>
<head>
<script type="text/javascript" src="getTeachers.js"></script>
</head>
<body>
<form>
<input type = "button" id="buttonId" value = "Press for Results" /><br />
</form>
<script type="text/javascript">
document.getElementById("buttonId").onclick=function(){getResults()};
</script>
<span id="results" /></span>
</body>
</html>
If your script refers to an ID on the page and the page has not been rendered (i.e. script is before HTML, or your script is executed with onload, rather then the DOM is ready) you can also get an error.
It doesn't. Most programming framework scatter scripts all throughout the page. I've only rarely seen problems because of that (and only from older browsers).
If you pull Javascripts in through XMLHttpRequest, like Diodeus said, it probably won't work. In my case, there was no error, the browser just ignores the new script(s).
I ended up using this, not terribly elegant but works for me so far:
http://zeta-puppis.com/2006/03/07/javascript-script-execution-in-innerhtml-the-revenge/
How to use execJS: http://zeta-puppis.com/2006/02/23/javascript-script-execution-in-innerhtml/
Note: Watch out for < in this line: for(var i=0;i<st.length; i++)
If you have an inline script (outside functions) located before functions it may call, you may get an error because they may not be not available yet. Not saying it is always going to happen, just that it may depending on browser type or version.
Javascript's scoping rules are similar to perl - you can call any function at the current or any higher scope level. The only restriction is that the function has to be defined at the time you call it. The position in the source is irrelevant - only the position in time matters.
You should avoid putting scripts in the <head> if possible as it slows down page display (see the link Alan posted).