Lifecycle of javascript file inside an html file - javascript

I have a very basic question about how javascript engine of a browser say chrome executes a javascript file embedded inside the html file. I am assuming, first the html page is rendered and then javascript is executed. My question is that when the engine reaches last line of the js file, what next?. Does all the callback methods of events remain active even after hitting the last line or after last line is hit, everything related to the js file is washed out from memory and js terminates?. Or does the js writer have to take care to put a loop in js file so that the js is functional and the last line is never hit.

Does all the callback methods of events remain active even after hitting the last line?
Yes.
does the js writer have to take care to put a loop in js file so that the js is functional and the last line is never hit?
No; in fact such an endless loop would provide a pretty bad user experience.
More generally speaking: it's very easy to try out these things and see for yourself. All you need is a browser and a text editor :-)
(Or even just an in-browser editor like codepen.io or jsfiddle.net or a bunch of others.)

Related

How to make a javascript logic not visible in page resource in angularjs?

I am working on a angularjs module in which we are trying to avoid a particular piece of logic in the view source on the browser. I have just given the skeleton code where the logic written inside script tags should not be shown in the page source of the browser.
<html ng-app="myApp">
<head>
<script>
if(something){
do something...
}
<script>
</head>
<body></body>
</html>
Is there any way in angularjs or javascript such that the logic written inside script is not visible in view page source on browser?.
This is not possible as the code needs to be executed by the browser, thus transferred to the client. Anyone can read/copy your code.
The most you can do is to use uglify or similar tool to minify your code. This will have to advantages for you. First, your code will be hard to read for others who might want to exploit your application. But keep in mind, it is still not impossible to understand your code even when minified - it just takes more time. And second, your scripts will become smaller thus making your page load slightly faster.
One more solution is make it look a bit complex so the user trying to read it does not understand it(in case you are not interested in making a minfied version)
Store all the Variables required in a separate file and access them form that file.
Even your base URL should be stored as global variable.
These are some options which you can use but making a minfied code is best practice.
You can't hide code to your client. It is executed in the client browser.
The best thing you can do here is to minify your code. It will make it unreadable without parsing it. Also, the code will be smaller, and will be loaded by the browser faster.
As a side note, luckily all the code is visible: imagine if malicious code could be executed without you know it.

What exactly is considered inline javascript? (in review of speed/efficiency cache comparison)

I have a lot of inline javascript, but nothing more then calls to functions such as:
<form id="some_id" style="x" method="post" onsubmit="return someFunction(this);"></form>
or "onchange", "onkeyup". I also have some scripts (not many) written inside <script> tags in html and all of the rest is external. The inside calls just as explicit above are all called to external script functions.
I opted to do this because found it more practical considering many async calls with element insertion and needed listeners to register those changes. This is, $.on("form onsubmit", function(){ would not apply to new elements appended async without a listener.
I'm building new elements in the server side due to my template structure and append them directly on the ajax callback.
My main file.js (external) is sitting at 1832 lines and and my index file which includes file.js has about ~500, ~350 with inline javascript as shown above.
This said:
Would it be considered a huge flaw to leave inline javascript as shown above (yes I know google does that) or could it be considered acceptable even by high standards?
Considering "inline javascript is not kept in cache", what does that mean exactly? Each time the user requests the web page he fetches the whole "onsubmit" in the line above? Or am I missing the meaning of this sentence.
Sorry if the question is vague but I'm quite thinking I had most of my service barely done and don't know if I should go over this or not at all :( thank you very much.
It's really hard to define "huge flaw" so let's just stick to pro's and con's of keeping the code "as-is":
Pro's :
Your current code works : No additional work is needed.
Con's :
Harder to debug : you JS is split on many places, a bug will be harder to track using the browser debug tools.Especially for more experienced JS developers who "expect" (or at least hope) the code to be organised following the good practices, like separating HTML, JS and CSS.
Speed : Your clients have to download and parse the additional JS with each query. If you were able to factorize all these methods calls in the main JS file, this would not be needed.
Modularity : all the methods you are calling from the HTML have to sit in the global namespace. The script you have written will be harder to reuse.
So basically, I would keep the code like this if the website is meant to be developed by you only, won't be used by million people and if you do not hope to reuse any of this code on another project.
If any of these condition is not met, I would refactor the code.
Also, refactoring the code, and learning how to correctly bind handler is a very good exercice if you plan on learning some more javascript.
$('body').on('onsubmit', 'form', function(){});
This will deal with any future changes to the DOM.

Page-level execution of JavaScript when serving concatenated files

Scenario:
A web site with x number of pages is being served with a single, concatenated JavaScript file. Some of the individual JavaScript files pertain to a page, others to plugins/extensions etc.
When a page is served, the entire set of JavaScript is executed (as execution is performed when loaded). Unfortunately, only a sub-section of the JavaScript pertains directly to the page. The rest is relevant to other pages on the site, and may have potential side-effects on the current page if written poorly.
Question:
What is the best strategy to only execute JavaScript that relates directly to the page, while maintaining a single concatenated file?
Current solution that doesn't feel right:
JavaScript related to a specific page is wrapped in a "namespaced" init function for that page. Each page is rendered with an inline script calling the init function for that page. It works hunky-dory, but I would rather not have any inline scripts.
Does anyone have any clever suggestions? Should I just use an inline script and be done with it? I'm surprised this isn't more of an issue for most developers out there.
Just use an inline script. If it's one or two lines to initialize the JavaScript you need that's fine. It's actually a good design practice because then it allows re-use of your JavaScript across multiple pages.
The advantages of a single (or at least few) concatenated js files are clear (less connections in the page mean lower loading time, you can minify it all at once, ...).
We use such a solution, but: we allow different pages to get different set of concatenated files - though I'm sure there exists different patterns.
In our case we have split javascript files in a few groups by functionality; each page can specify which ones they need. The framework will then deliver the concatenated file with consistent naming and versioning, so that caching works very well on the browser level.
We use django and a home-baked solution - but that's just because we started already a few years ago, when only django-compress was available, and django compress isn't available any more. The django-pipeline successor seems good, but you can find alternatives on djangopackages/asset-managers.
On different frameworks of course you'll find some equivalent packages. Without a framework, this solution is probably unachievable ;-)
By the way, using these patterns you can also compress your js files (statically, or even dynamically if you have a good caching policy)
I don't think your solution is that bad although it is a good thing that you distrust inline scripts. But you have to find out on what page you are somehow so calling the appropriate init function on each page makes sense. You can also call the init function based on some other factors:
The page URL
The page title
A class set in the document body
A parameter appended to your script URL and parsed by the global document ready function.
I simply call a bunch of init functions when the document is ready. Each checks to see if it's needed on the page, if not, simply RETURN.
You could do something as simple as:
var locationPath = window.location.pathname;
var locationPage = locationPath.substring(locationPath.lastIndexOf('/') + 1);
switch(locationPage) {
case 'index.html':
// do stuff
break;
case 'contact.html':
// do stuff
break;
}
I'm really confused exactly why it doesn't feel right to call javascript from the page? There is a connection between the page and the javascript, and making that explicit should make your code easier to understand, debug, and more organized. I'm sure you could try and use some auto wiring convention but I don't think it really would help you solve the problem. Just call the name spaced function from your page and be done with it..

multiple versus single script tags

Is there any difference (performance, best practices, etc) between using a single script tag with embedded code in it, or using multiple script tags with the same code spread all over the HTML?
For example:
<script>
foo();
</script>
...
<script>
bar();
</script>
versus:
<script>
foo();
bar();
</script>
Thanks
With inline script like what you quoted, there's unlikely to be much difference; however, every time the browser's HTML parser encounters a script tag, it:
Comes to a screeching halt
Builds up a string of the the text in the tag up until the first time it sees the string "</script>"
Hands that text off to the JavaScript interpreter, listening for output the interpreter sends it when you do a document.write
Waits for the interpreter to finish
Inserts the accumulated output received into the parsing stream
Continues its parsing
So increasing the number of times this sequence has to occur can, in theory, increase your page load time. It also affects the degree to which the parser can "look ahead" in the token stream, which may make it less efficient.
All of which sounds really dramatic, but you'd have to profile a real page in the various browsers you care about to determine whether it had a real-world impact.
So in summary, combine them as much as you reasonably can. If you can't reasonably combine a couple, don't worry about it too much until/unless you see a real-world problem.
The above is for inline script. Naturally, if you have several script tags referring to a bunch of external JavaScript files, you'll also have the issue that each of those files has to be downloaded, and initiating an HTTP request is an expensive thing (comparatively) and so it's best, in a big way, to combine those into a single file.
Some other things to consider:
Having lots of script tags scattered throughout your HTML may make it difficult to do maintenance on the script
Separating your HTML and script into separate files helps you limit the degree to which they're coupled, again aiding maintenance
Putting script in a separate file makes it possible to run that file through minifiers/compressors/packers, minimizing the size of your code and removing comments, thus leaving you free to comment in your source code knowing those comments will be private
Putting your scripts into external files gives you the opportunity to keep things separated by functionality, and then combine them into a single file for the page (compressed/minified/packed) for efficient delivery to the browser
More:
YUI's "Best Practices for Speeding Up your Web Site"
Google's "Web Performance Best Practices"
Combining your scripts as much as possible is better in my opinion. Some browsers have to pause rendering while executing script blocks. Check out answer at: Javascript Performance: Multiple script blocks Vs single bigger block
Up to this point all of the JavaScript Code was in one tag, this does not need to be the case.
You can have as many tags as you would like in a document.
The tags are processed as they are encountered.
Hope this helps.
Some argue that it's best practice is to combine all scripts in a single script block or a single script file, load only the javascript that is really needed and load it as late as possible to not slow down the rendering of html.
Apart from that i am sure that using a single script block loads faster than using multiple script blocks since they have to be evaluated individually. However this difference might not be recognizable.
I USE multiple tags. One for Slideshow of Images and another for Slideshow of Texts, so I can have both on the same web page - slideshow of images and slideshow of texts.

Putting JavaScript at the end of the page produces an error

I recently read that for a faster web page load it's a good practice to put the JavaScript links at the end. I did, but now the functions of the referenced file doesn't work. If I put the link at the beginning of the page, everything is fine.
Does this thing of putting JavaScript at the end work only under certain circumstances?
I went through some testing with this as well. If you are loading a Javascript file it is faster to put it at the end BUT it does come with some important caveats.
The first is that doing this often made some of my visual effects noticeable. For example, if I was using jQuery to format a table, the table would come up unformatted and then the code would run to reformat it. I didn't find this to be a good user experience and would rather the page came up complete.
Secondly, putting it at the end made it hard to put code in your pages because often functions didn't exist yet. If you have this in your page:
$(function() {
// ...
});
Well that won't work until the jQuery object is defined. If it's defined at the end of your page the above will produce an error.
Now you could argue that all that styling code could be put in the external file but that would be a mistake for performance reasons. I started off doing that on a project and then found my page took a second to run through all the Javascript that had been centralized. So I created functions for the relevant behaviour and then called the appropriate ones in each page, reducing the Javascript load run time to 50-200ms.
Lastly, you can (and should) minimize the load time of Javascript by versioning your Javascript files and then using far-futures Expires headers so they're only loaded once (each time they're changed), at which point where they are in the file is largely irrelevant.
So all in all I found putting putting the Javascript files at the end of the file to be cumbersome and ultimately unnecessary.
You do have to pay attention to the ordering, but libraries like JQuery make it easy to do it right. At the end of the page, include all the .JS files you need, and then, either in a separate file or in the page itself, put the Jquery calls to act on the page contents.
Because JQ deals with css-style selectors, it's very easy to avoid any Javascript in the main body of the page - instead you attach them to IDs and classes.
This is called Unobtrusive Javascript
Every Yahoo YUI example file I remember has almost all the JavaScript at the end. For example,
Simple Event Handling
Basic Drag and Drop
JSON: Adding New Object Members During Parsing
It looks like Yahoo Practice is roughly "library code at the beginning of <body>, active code at the end of <body>."
Beware, though, this may result in the Flash of Unstyled Content syndrome.

Categories