What is this script doing? [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 9 years ago.
Improve this question
I have a ASP.NET MVC 4 application.
This referrs a Js file like so:
<script type="text/javascript" src="http://localhost:32967/Scripts/MyScripts/Myscript.js"></script>
There was a blocking time seen in the browser while downloading this script.
Googling for this, I found a reference here
When this script is added the blocking is gone.
In fact there is no blocking seen for any more script references added.
This had a major speed boost.
Can someone please explain what this script does?
If blocking can be avoided by doing this then why is this not a best practice?
[Update]
I have changed the script name from Reference.js to MyScript.js as it's causing confusion with the other question with the _reference.js.
Here are the contents of this file:
var urls = {
commonUrl: "http://localhost:32944/",
myappurl: "http://localhost:32967/",
productUrl: "http://localhost:49880/"
}
That's all there is in that file.
Regards.

References.js is only used by the Visual Studio IDE as a list of files to which provide Intellisense for. It is not included in any HTML file as a script reference by the basic template, as I interpret you claim in your question.
If anything, adding the script reference should slow down load time. I'm going out on a limb here and claiming your measurements are wrong - that adding this script in no way can speed up loading time of any web page.
edit: I see you have updated your question now. If this indeed is not _references.js, then you need to provide the content of the file for us to give an answer.

You ask two questions:
What does it do? It fools the browser in thinking there are no script references in this HTML page, only a single inline script. By doing this it circumvents the standard load procedure which results in the scripts being loaded at a later point than normal, and asynchronously. Why exactly this results in asynchronous loading you must ask the implementors of the different browsers. It may not be true for all.
Why is it not best practice? I can think of multiple reasons:
It comes with side effects
It is a more verbose, less readable format
It breaks the HTML standard
It breaks SEO and other machine parsing of the HTML
As for #1: By loading and running asynchronously you no longer have control over which script executes first. There may be dependencies between the scripts, which will result in runtime errors when done in wrong order. If you could solve the problem of running in order while still loading asynchronously (totally doable), you'll be fine though.
Then again, you should rather push the browser implementors to fix this instead of implementing this rather ugly hack. There are many other more viable ways of improving page load time better than this. Caching, minifying and bundling are three that jumps to mind.
Lastly I'm assuming you have added a working implementation of the script referenced at the webdigi blog. The blog itself is good at explaining the concept, but awful on code examples as it does not provide insight in what the poorly named variables n,k,e, g and C should represent. Here is a working implementation for reference and context of what I'm talking about, which loads JQuery and JQuery UI. Note that since JQuery UI depends on JQuery core being loaded first, this example will only work half the time:
<html>
<head>
<script>
var headNode = document.getElementsByTagName("HEAD")[0];
// Jquery
var c1 = document.createElement("script");
c1.type= "text/javascript";
c1.src = "http://code.jquery.com/jquery-2.1.0.min.js";
// JQuery UI
var c2 = document.createElement("script");
c2.type= "text/javascript";
c2.src = "http://code.jquery.com/ui/1.10.4/jquery-ui.min.js";
headNode.appendChild(c1);
headNode.appendChild(c2);
</script>
</head>
<body>
Content goes here
</body>
</html>

Related

Javascript/jQuery best practice for web app: centralization vs. specification [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
Imagine a web app that have dozens of page groups (pg1, pg2, ...) and some of these page groups need some JavaScript code specific only to them, but not to the entire app. For example, some visual fixes on window.resize() might be relevant only in pg2 but nowhere else.
Here are some possible solutions:
1/ Centralized: having one script file for the entire app that deals with all page groups. It's quite easy to know if relevant DOM object is present and so all irrelevant pages simply do a minor extra if().
Biggest advantage is that all JS is loaded once for the entire web app and no modification of the HTML code is needed. Disadvantage is that a additional checks are added to irrelevant pages.
2/ Mixed: the centralized script checks for the existence of a specific function on a page and launches it if it exists. For example we could add a
if (typeof page_specific_resize === 'function') page_specific_resize();
The specific page group in this case will have:
<script>
function page_specific_resize() {
//....
}
</script>
Advantage is that the code exists only for relevant pages and so isn't tested on every page. Disadvantage is additional size for the HTML results in the entire page group. If there are more than a few lines of code, the page group might be able to load an additional script specific to it but then we're adding an http call there to possibly save a few kilos in the centralized script.
Which is the best practice? Please comment on these solutions or suggest your own solution. Adding some resources to support your claims for what's better (consider performance and ease of maintenance) would be great. The most detailed answer will be selected. Thanks.
It's a bit tough to think on a best solution since it's an hypothetical scenario and we don't have the numbers to crunch on: what are the most loaded pages, how many are there, the total script size, etc...
That said, I didn't find the specific answer, Best Practice TM, but general points where people agree on.
1) Cacheing:
According to this:
https://developer.yahoo.com/performance/rules.html
"Using external files in the real world generally produces faster
pages because the JavaScript and CSS files are cached by the browser"
2) Minification
Still according to the Yahoo link:
"[minification] improves response time performance because the size of the downloaded file is reduced"
3) HTTP Requests
It's best to reduce HTTP calls (based on community answer).
One big javascript file or multiple smaller files?
Best practice to optimize javascript loading
4) Do you need that specific scritp at all?
According to: https://github.com/stevekwan/best-practices/blob/master/javascript/best-practices.md
"JavaScript should be used to decorate your site with additional functionality, and should not be required for your site to be operational."
It depends on the resources you have to load. Depends on how frequently a specific page group is loaded or how much frequently you expect it to be requested. The web app is single page? What each specific script do?
If the script loads a form, the user will not need to visit the page more than once. User will need internet connection to post data later anyway.
But if it's a script to resize a page and the user has some connection hiccups (ex: visiting your web app on a mobile, while taking the the subway), it may be better to have the code already loaded so the user can freely navigate. According to the Github link I posted earlier:
"Events that get fired all the time (for example, resizing/scrolling)"
Is one thing that should be optimized because it's related to performance.
Minifying all the code in one JS file to be cached early will reduce the number of requests made. Also, it may take a few seconds to a connection to stablish, but takes milliseconds to process a bunch of "if" statements.
However, if you have a heavy JS file for just one feature which is not the core of your app (say, this one single file is almost n% the size of the total of other scripts combined), then there is no need to make the user wait for that specific feature.
"If your page is media-heavy, we recommend investigating JavaScript techniques to load media assets only when they are required."
This is the holy grail of JS and hopefully what modules in ECMA6/7 will solve!
There are module loaders on the client such as JSPM and there are now hot swapping JS code compilers in node.js that can be used on the client with chunks via webpack.
I experimented successfully last year with creating a simple application that only loaded the required chunk of code/file as needed at runtime:
It was a simple test project I called praetor.js on github: github.com/magnumjs/praetor.js
The gh-pages-code branch can show you how it works:
https://github.com/magnumjs/praetor.js/tree/gh-pages-code
In the main,js file you can see how this is done with webpackJsonp once compiled:
JS:
module.exports = {
getPage: function (name, callback) {
// no better way to do this with webpack for chunk files ?
if (name.indexOf("demo") !== -1) {
require(["./modules/demo/app.js"], function (require) {
callback(name, require("./modules/demo/app.js"));
});
}
.....
To see it working live, go to http://magnumjs.github.io/praetor.js/ and open the network panel and view the chunks being loaded at runtime when navigating via the select menu on the left.
Hope that helps!
It is generally better to have fewer HTTP requests, but it depends on your web app.
I usually use requirejs to include the right models and views I need in each file.
While in development it saves me considerable time on debugging (because I know which files are present), in production this could be problematic considering the number of requests.
So I use r.js, which is conceived especially for requirejs, to compile my JS files when it's time for deployment.
Hope this helps

What is the big block of javascript that i see at the beginning of some html pages?

I'm trying to increase my literacy of source code, however often times when I view page source for a site i will find a huge wall of what appears to be javascript code.
A good example would be this site:
http://www.torontossc.com/
When I view the page source, I have no idea how to deal with that huge wall, so I have a few questions/logical deductions.
The code wall is in <script> tags, so I'm assuming it must be javascript. But I'm confused about why it's presented in such an unreadable/cluttered format. Surely there must be a reason for that.
I downloaded the source code and looked at the html page, and noticed that when I'm not viewing the source at run time, that block isn't there- There's only an externally referenced script in its place. So is the wall of code I'm seeing the actual script itself, that runs on page load?
I did further digging and found out that the script is part of the facebook sdk. So does this mean that any time i see a wall of code like this, it's usually a script imported for use as part of an API/for integration with another website? If that's the case, then should i assume that the clutter and density of it is just for compactness
If my above assumptions are correct, then would learning javascript allow me to fully understand that code wall?
I hope I've answered my own question through deduction, but hopefully someone can confirm.
Thanks!
The code wall is in tags, so I'm assuming it must be javascript.
Yes, it's clearly printed right there: <script type="text/javascript">.
But I'm confused about why it's presented in such an unreadable/cluttered format. Surely there must be a reason for that.
It's minified, a form of obfuscation which makes JavaScript smaller to download and more difficult to reverse engineer.
I downloaded the source code and looked at the html page...
That probably broke a lot of things. You can't just download a page without downloading all of it's relatively-referenced paths.
So does this mean that any time i see a wall of code like this, ...
No, there's nothing you can tell about the code except that it's
inline
minified
If my above assumptions are correct, then would learning javascript allow me to fully understand that code wall?
No, nobody writes code that way, and nobody (easily) understands code written that way. A computer compressed/minified the code, and to understand it you need to learn JavaScript, and then unminify the code, which is a far from perfect process. Many forms of minification are "destructive" in that it's impossible to arrive back at the original source code. Human-readable tokens are often turned into single characters, and there is no way to undo this process, the original human-readable names are lost.

Getting Javascript via AJAX [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I would like to know what if i get all my scripts(not vendor) via AJAX request and what's good or bad about it. Would browser cache the response or server would send my script with every request as if user never been to my site?
Performance-wise would that be better, than storing all scripts in footer.
Getting scripts via AJAX is a bit of confusion in terms, you can use JavaScript to create additional script elements to load extra scripts into the page - which can also be done so asynchronously so it will not block the rendering or download of the page. Take a look for example at the following:
var script = document.createElement('script');
script.src = 'myscript.js';
document.head.appendChild(script);
It creates a new script element, assigns a source and the appends it to the head section of the document. If this was added to the end of the document then the script would be downloaded without having blocked the page loading.
This simple idea is the basis for all (that I know of) front-end JS dependency management - the idea that the requested page only download the assets it needs. You might have heard of JS module definitions such as AMD and CommonJS and that's a huge topic, so I'd recommend taking a read of Addy Osmani's "Writing Modular JavaScript With AMD, CommonJS & ES Harmony" article.
In answer to whether or not they will be cached the answer is yes--in general--though caching depends on many factors both on the server and the user's browser. The individual requests will still need to be made on each subsequent page load which can be slower than one big individual file on a flaky connection. The decision really is down to how users may be accessing your site and whether or not a slight speed decrease initially is worth it vs. developer authoring and maintenance. You can always go for the latter than later on move to the former.
In essence, <script> is by default pulling data into your page synchronously. That might be an issue when scripts are placed in the head section since it might be a blocker for showing your body's content.
Pulling in javascript asynchronously by ajax might usually come handy in case specific minor conditions are met, i.e. most of the users won't use your script in the first place. Let's say you're having a page and should you be logged in as an admin, some additional script is pulled in to handle your admin UI. Or such.
But generally speaking, there's no real advantage in ajaxing javascripts and should you want to avoid broken dependencies (your script being pulled in earlier than your jQuery library, for instance), just stick with your already optimal solution: placing your javascripts as the last thing beforing closing the body tag.
Note also there's new async attribute in the HTML5 draft where it's possible to get script asynchronously ((and therefore speed up loading in theory) even without using AJAX magic. As always though, it's only supported by modern browsers, kicking IE9 and older out of the game.
Hope it helps!

Why doesn't javascript have a better way to include files?

I've seen a few ways that you can make a javascript file include other javascript files, but they all seem pretty hacky - mostly they involve tacking the javascript file onto the end of the current document and then loading it in some way.
Why doesn't javascript just include a simple "load this file and execute the script in it" include directive? It's not like this is a new concept. I know that everyone is excited about doing everything in HTML5 with javascript etc, but isn't it going to be hard if you have to hack around omission of basic functionality like this?
I can't see how it would be a security concern, since a web page can include as many javascript files as it likes, and they all get executed anyway.
The main problems with the current inclusion system (ie, add additional script tags) involve latency. Since a script tag can insert code at the point of inclusion, as soon as a script tag is encountered, further parsing has to more-or-less stop until the JS downloads and is executed (although the browser can continue to fetch resources in parallel). If the JS decides to run an inclusion, you've just added more latency on top of this - now you can't even fetch your scripts in parallel.
Basically, it's trying to solve a problem that doesn't exist (since JS can already tack on additional script tags to do an inclusion), while making the latency problem worse. There are javascript minifiers out there that can merge JS files; you should look into using those instead, as they will help improve latency issues as well.
Actually, YUI 3 solves this problem beautifully. Feel free to check out the documentation: http://developer.yahoo.com/yui/3/yui/#use (that's the specific Use function which does this magic). Basically it works like this:
You define modules
When you create the core YUI object with YUI(), you specify which modules your code needs
Behind the scenes, YUI checks if those modules are loaded. If not, it asynchronously loads them on the page.
I've also read that the jQuery team's working on something similar (someone back me up here).
As to the philosophical argument that it'd be nice if this was built in, I think that may be a good feature. On the other hand, the simplicity of javascript is nice too. It allows a much lower point of entry for beginning programmers to do their thing. And for those of us that need it, great libraries like YUI are getting better every day.
the requirejs project attempts to solve this problem, please see for example
http://requirejs.org/docs/why.html
(I don't use it yet, though)

Detecting JavaScript on an HTML page using Python

I'm currently working on a network security project that checks for XSS vulnerabilities on a website, which hopefully can be used for pen-testers out there (in case you don't believe me and think I'm some kinda script kiddy, here's the class website: http://netsec.cs.northwestern.edu/projects/).
So, I'm having trouble detecting JavaScript on a given HTML page. I spent many hours installing PyV8 and V8 and it seems that they can evaluate simple JavaScript statements. However, for more 'complex' JavaScript problems, for example, an alert box, PyV8 does not seem to support it. So, I doubt if I can feed PyV8 some arbitrary JavaScript code and expect it to give me the corresponding JavaScript output.
I did find this JS server/client in DrEval but it doesn't seem to work in the latest revision of V8/PyV8.
Please help! My project is due in about a week from today and no one in the class seems to be able to help me because this is a rather strange problem..
Uhmm.. And I apologize in advance if this question has been answered somewhere else before. I did search for this topic for at least 2 hours..
Thanks in advance for the responses!
A incredibly hacky way would be to look for "text/javascript" in the source of the webpage.
import urllib2
if urllib2.urlopen('http://www.google.co.uk').read().find('text/javascript') == 0:
print "It has js."
This is NOT the best answer I would be happy to hear from someone who does know the correct way to do it.
I'm not really sure what you want to do but here are some thoughts:
If you want to run JavaScript code in the context of a web page, you need a browser or an emulation of one. Try envjs. It needs Java, though, because it needs a JavaScript interpreter.
I'm not aware of a library which offers the same functionality for Python. Maybe you can fix that. envjs is written mostly in JavaScript but it needs some support functions from the interpreter (printing to the console, downloading data, opening files).
XSS vulnerabilities happen if you can inject JavaScript code into a page, no matter what code already exists. So you need to check all fields of a form, post the form to the server and then check that it properly escapes all values on the next page.
PyV8 is Python binding of V8 javascript engine. It can evaluate even the most complex javascript code. It is also being used by Google Chrome.
That being said, there are a few things you need to do to make it work properly. First of all, PyV8 is a javascript engine only. It does not construct the DOM. Thus, you need to create a DOM yourself and run the PyV8 context with it.
Also, you have said that the alert function does not work. The alert(); function is part of the DOM, it is shorthand of window.alert();. So, you have to specify each function and property in DOM.
PyV8 source comes with a simple DOM. You can download it from http://code.google.com/p/pyv8/source/browse/

Categories