How does a browser AUTOMATICALLY convert "Page Source" Javascript to HTML? - javascript

Now that I understand how to access both the raw HTML+Javascript (as received by HTTP GET) and the rendered-result of auto-processing of the Javascript upon page load completion, I need to understand how it is being done:
Is there a specific Javascript
function, embedded in the raw HTTP
GET resonse, that the browser looks
for, and when found, it simply calls
it? (in other words, is it the
responsibility of the web page
programmer to instruct the browser
to scan the raw content and
substitute all non-interactive
Javascript to HTML?)
Does the browser analyze the entire
page, looking for certain cues, and
then decides what to convert? If so,
what are these cues and how it is
being done?
Being totally fresh in this subject, it is quite possible that none of the above applies and the trick is done in completely different manner. If this is indeed the case, would you be so kind as to guide me how to re-phrase the question?

The HTML specification defines the circumstances under which Javascript runs. Some javascript it attached to onSOMETHING attributes, and it runs at the defined time. One important example of which is 'onload'. Other Javascript is simply in top-level blocks inside of <script> elements. By spec, the browser runs that whenever it feels like, just in order.
There's no 'conversion' and no 'substitution'. Javascript is a programming language. The browser runs the code. In some cases, the code does interact with the DOM tree to produce displayable contents. In other cases, it does not (e.g. sending information over a connection).

HTML gets loaded sequentially. When a script tag is discovered, the browser executes the script. For example:
<div id="test"></div>
<script type="text/javascript">document.getElementById("test").innerHTML = "Hi there!";</script>
However, if you have the following document
<script type="text/javascript">document.getElementById("test").innerHTML = "Hi there!";</script>
<div id="test"></div>
nothing would happen, because at the time the browser executes the script, the browser hasn't discovered the test div yet.

When a web browser parses an HTML page, if it encounters a <script> element, it stops parsing the HTML, and runs the JavaScript in (or linked to by) the <script> element immediately*.
The JavaScript code can amend the page’s DOM (Document Object Model — the programmatic representation of the HTML that JavaScript can access), and thus change the rendered HTML that’s shown by the browser. (It can also assign functions to built-in event handlers on DOM nodes, so that some JavaScript can be run e.g. when the user clicks on a link, or when the document has finished loading.)
It is thus indeed entirely the responsibility of the web page programmer to do this. Browsers don’t guess what to do with the downloaded JavaScript. They run and obey it.
(* That’s a bit of a simplification: the defer attribute can prevent the script from being run immediately.)

I red your last thread.
Let me tell you this,
A browser has a HTML version of the page and a DOM (Document Object Model) version of it.
Whenever a Javascript changes something, it's changed in the DOM. At first DOM is generated from page HTML,
So Javascript doesn't change page source.
Your question here is totally irrelevant, Since the browser does this operation for loading a page :
HTTP request to recieve data (possibly an HTML document)
Parse the received data (if it is HTML)
Look for other resources in the parsed data (links to other javascript, css, images, etc.)
Download the remaining resources (loop back to step 2)
Generate the DOM, run the CSS and Scripts, show images.
The browser starts running all the javascript from top to bottom of the received data. You can also assign Javascript function to Events of elements on the page, so that when the event is triggered, The javascript function specified is automatically called.
Parsing a HTML and running its javascript has nothing to do with HTTP protocol and can be done solely on your own computer (opening a HTML file on your disk).

The browser parses the HTML code, and upon encountering JavaScript code enclosed in proper <script> tags, it evaluates the encountered JavaScript which can result in document structure and/or content changes that become visible to the user.

Is there a specific Javascript function, embedded in the raw HTTP GET resonse, that the browser looks for, and when found, it simply calls it? (in other words, is it the responsibility of the web page programmer to instruct the browser to scan the raw content and substitute all non-interactive Javascript to HTML?)
No. There are many. See http://dev.opera.com/articles/view/creating-and-modifying-html/
(Actually, you should probably start at http://dev.opera.com/articles/view/1-introduction-to-the-web-standards-cur/#toc )
Does the browser analyzes the entire page, looking for certain cues, and then decides what to convert? If so, what are these cues
<script>
and how it is being done?
DOM

Related

Difference in performance and memory footprint between referencing a Javascript using src or directly injecting it in the HEAD

What are the differences in performance and memory footprint , if any, in these different approaches:
1. Using Src
<script type='text/javascript" src="1MBOfjavascript.js"></script>
2. Directly injecting in the Head
$('head').append("<script type='text/javascript'>1MBOfJavascriptCode</script>");
I'm interested because we are developing a Cordova App where we use the second method to Inject to the DOM a previously downloaded Javascript bundle read from the HTML Local Storage.
Given that the script will probably grow in size, I'd like to know if with the second method I could incur in some memory issues or other DOM problem.
I believe the overhead in such cases should be insignificant as the main processing/memory consumption is based on how the actual script works. Ie the memory used by file would be the total size of the script which is what 1MB at max? However during execution the same script can use up 100MB easily.
Anyways , coming to the point.
Plain text inclusion would be better if it has to be included in all cases as it skips a script execution and also does not cause re-rendering by browser after the append.
Append option should be used in cases where you only need the script under specific conditions on client side and do not load it un-necessarily.
The browser goes through all elements before to render the page so I would imagine it is exactly the same, if anything if you had scripts after the page is downloaded chances are that you will get errors of the type "call to undefined functions" if you call onto a function that you have added after the load.
My advise would be add them at load using src but keep things tidy.
Javascript impact a lot depending upon how and where you are loading your file, there are many ways to load a file or code.
First method you mentioned is an conventional way to load javascipt file that is load file using src and usually its loaded before closing </head> tag but now a days it is in trend to load file befor your </body> tag. it speeds up application load and prepare DOM faster.
second method is not obviously a good way to load javascript at first as there can be some code that should be working only after your DOM is ready and as here you are loading your javscript with javascript/jquery append which depends upon your jquery file loading which will delay your code execution. and there might be possible that some of your code will not have desired output (depending upon how you have called functions and how much they are dependent upon DOM ready )
I would prefer to load a javascript file with first method and at the bottom of the page/app if possible.
asyncrounous loading can also be tried.
i think because browser behavior after retrieving response from any web server
will try to parse all the elements first for building the DOm, after the DOM are ready then your script would be executed, based on this it is obvious its the main
reasons is which is the first
will be executed first than injecting it.
About the second method
i think javascript engine in each browser can handle that thing easily and withouth any problem. the engine does not care about the size actually it only about how long the script will be loaded and then executed. what will be the issue is when you try injecting any elements into DOM is when you try to do it in loop there might be a memory problem.
when you say big javascript files yeah we should think about the memory. but
about the method you previously said its just about which are executed first.
thats my opinion

Does inline javascript block the UI thread?

I read this nice article on how external scripts block the UI thread but it wasn't clear to me whether the blocking is actually due to the presence of the <script> tag or the src='/myscript.js' src attribute.
My question is does inline javascript (lacking a src attribute declaration), for example this:
<script type='text/javascript'> alert('am i blocking too?');</script>
or this:
<script type='text/javascript'> var php='<?=json_encode($myObj)?>';</script>
also block the UI thread?
Any loading of a JS file or any execution of any JS (whether in an external file or inline) will block the UI thread.
The exception for the <script> tag is an asynchronous load where the script will load and execute asynchronously in the background.
There are also "deferred" loads (i.e. the defer attribute) which tells the browser not to actually execute the JS therein until the rest of the page has loaded.
Outside of web workers, which are their own beast, consider the HTML web page and associated Javascript as single threaded.[1]
Thus, if any javascript is running on the page, then the entire user interface is blocked. Things like window.alert(), window.confirm() and window.prompt() block the entire UI until they are cleared, but even an infinite loop will freeze the browser window[2] until it has finished.
EDIT -- based on comments and edit to the question:
The link provided in the original question doesn't refer to the execution of Javscript running, but the sync vs async nature of Javscript loading. I'll give you one example of why such blocking may occure.
In the way-back days of Javscript, the function document.write() was the only way to have Javascript interact with the web page. As such, when the web page came across a request for a Javascript file to load, the browser had to put everything else on hold -- just in case the Javascript file used document.write to inject something into the stream.
In today's world, this doesn't happen as much and so browsers give the page designer a way to say 'I promise this Javascript file doesn't care exactly when it is loaded and it won't use document.write() or anything else tricky. You don't have to freeze until it is done.
This is why modern web browsers have a defer and async attributes.
Opera is special, but we'll ignore that.
Or entire browser, depending
alert() or any other prompting actions will block the thread until the user responds to the prompt. No matter where they are...
Update ( regarding the comment ) :
A browser window parses the HTML and runs the JS with a single thread.. so anything in the javascript code that will take time to complete will block the thread.. no matter what it is.. It can be an alert or an AJAX Request or anything else..

How do I get the path of the currently running script with Javascript?

We have an IE extension implemented as a Browser Helper Object (BHO). We have a utility function written in C++ that we add to the window object of the page so that other scripts in the page can use it to load local script files dynamically. In order to resolve relative paths to these local script files, however, we need to determine the path of the JavaScript file that calls our function:
myfunc() written in C++ and exposed to the page's JavaScript
file:///path/to/some/javascript.js
(additional stack frames)
From the top frame I want to get the information that the script calling myfunc() is located in file:///path/to/some/javascript.js.
I first expected that we could simply use the IActiveScriptDebug interface to get a stacktrace from our utility function. However, it appears to be impossible to get the IActiveScript interface from an IWebBrowser2 interface or associated document (see Full callstack for multiple frames JS on IE8).
The only thing I can think of is to register our own script debugger implementation and have myfunc() break into the debugger. However, I'm skeptical that this will work without prompting the user about whether they want to break into the debugger.
Before doing more thorough tests of this approach, I wanted to check whether anyone has definitive information about whether this is likely to work and/or can suggest an alternative approach that will enable a function written in C++ to get a stack trace from the scripting engine that invoked it.
Each script you load may have an id and each method of the script calling myfunc() may pass this id to myfunc(). This means that first you have to modify myfunct() and finally alter your scripts and calls.
This answer describes how I solved the actual issue I described in the original question. The question description isn't great since I was making assumptions about how to solve the problem that actually turned out to be unfounded. What I was really trying to do is determine the path of the currently running script. I've changed the title of the question to more accurately reflect this.
This is actually fairly easy to achieve since scripts are executed in an HTML document as they are loaded. So if I am currently executing some JavaScript that is loaded by a script tag, that script tag will always be the last script tag in the document (since the rest of the document hasn't loaded yet). To solve this problem, it is therefore enough just to get the URL of the src attribute of the last script tag and resolve any relative paths based on that.
Of course this doesn't work for script embedded directly in the HTML page, but that is bad practice anyway (IMO) so this doesn't seem like a very important limitation.

Running Javascript from external file loaded with AJAX

I've been trying to get this sorted all day, but really cant figure it out. I've got a page with <div id="ajax"></div> that is populated off a tab based menu pulling in a snippet of HTML code stored in an external file that contains some javascript (mainly form validation).
I've seen in places that I need to eval() the code, but then on the same side of things people say its the last thing to do.
Can someone point me in the right direction, and provide an example if possible as I am very new to jQuery / JavaScript.
Many thanks :)
pulling in a snippet of HTML code stored in an external file that contains some javascript (mainly form validation).
Avoid doing this. Writing <script> to innerHTML doesn't cause the script to get executed... though moving the element afterwards can cause it to get executed, at different times in different browsers.
So it's inconsistent in practice, and it doesn't really make any sense to include script anyway:
when you load the same snippet twice, you'd be running the same script twice, which might redefine some of the functions or variables bound to the page, which can leave you in extremely strange and hard-to-debug situations
non-async/defer scripts are expecting to run at parse time, and may include techniques which can't work when inserted into an existing document (in the case of document.write this typically destroys the whole page, a common symptom when trying to load third-party ad/tracking scripts).
Yes, jQuery tries to make some of this more consistent between browsers by extracting script elements and executing them. But no, it doesn't manage to fix all cases (and in principle can't). So don't ask it to. Keep your scripts static, and run any binding script code that needs to happen in the load callback.
If you fetch html via Ajax, and that html has a <script> tag in it, and you write that html into your document via something like $('#foo').append(html), then the JS should run immediately without any hassle whatsoever.
jquery automatically processes scripts received in an ajax request when adding the content to your page. If you are having a particular problem then post some code.
See this link
dataType: "html" - Returns HTML as
plain text; included script tags are
evaluated when inserted in the DOM.

Is Javascript parsed/interpreted on load? (IE)

I Know, for instance, that when Chrome downloads a Javascript file, it is interpreted and JITed.
My question is, when IE6,7,8, first download a Javascript file, is the entire thing parsed and interpreted?
My understanding was that only top level function signatures and anything executed in the global scope was parsed on load. And then function bodies and the rest were parsed on execution.
If they are fully parsed on load, what do you think the time savings would be on deferring the function bodies to be downloaded and parsed later?
They are fully parsed on load. (IE has to parse the script to know where each function body ends, of course.) In the open-source implementations, every function is compiled to bytecode or even to machine code at the same time, and I imagine IE works the same way.
If you have a page that's actually loading too slowly, and you can defer loading 100K of script that you're probably not going to use, it might help your load times. Or not—see the update below.
(Trivia: JS benchmarks like Sunspider generally do not measure the time it takes to parse and compile the code.)
UPDATE – Since I posted this answer, things have changed! Implementations still parse each script on load at least enough to detect any SyntaxErrors, as required by the standard. But they sometimes defer compiling functions until they are first called.
Because defining a function is actually an operation, yes, your entire javascript file is parsed, and all of the top-level operations are interpreted. The code inside of your functions is not actually executed until it's called, but it is parsed.
for example:
var i=0;
var print = function( a ) {
document.getElementById( 'foo' ).innerHtml = a;
}
Everything gets parsed in the above example, and lines 1 and 2 get executed. However, line 3 doesn't get executed until it's called.
There are little "perceptual games" you can play with your users, like putting the script tags at the bottom of the HTML instead of at the top, so that the browser will render the top of the page before it receives the instructions to download and parse the javascript. You could probably also push your function definitions into a document.onload function, so that they don't get executed until after the whole page is loaded and in memory. However, this could cause a "flash of unstyled content" if your javascript is applying visual styles to things (such as jQuery UI stuff).
Yes, on all browsers the downloading of the resource blocks everything else on the page (CSS downloading, other JS downloading, rendering) if done with a <script> tag.
If you're loading all the javascript at the beginning or throughout your page you will see hiccups as a request is about 50ms and the parsing for a library file or something similar could be more than 100ms. 100ms is used as the standard for which anything greater will be noticed as "lag" by the user.
The time savings may be negligible, but the slight loss of user experience if there are pauses when your page is loading may be significant depending on your situation.
See LABjs' site for a lot of articles and great explanations on the benefits of deferring loading and parsing.
What do you mean by "downloads"? When it's included with tag, or when it's downloaded through XMLHttpRequest?
If you mean the inclusion by script, then IE interpret all js files at once. Otherwise you will be not able to call functions in that file or see syntax error message.
If you mean download by XMLHttpRequest, then you have to evaluate the content of the file yourself.

Categories

Resources