This question already has answers here:
JQuery - $ is not defined
(36 answers)
Closed 6 years ago.
i'm trying to load javascript asynchronous in the head section. After page loading in developer console i have error that "jQuery is not defined". After one or two refreshes scripts load and work perfectly. Without "async" inside script tag also works. Why this happens and is there any way to fix this. Thanks in advance
As Dellirium said, JQuery needs to be placed before the javascript code that requires it. You could try placing the JQuery in the <head> and the script you're running at the end of the body tag <body>.
You could add a function to be executed when jQuery is loaded.
<script src="jquery.js&callback=start"</script>
In which &callback=start executes the start() function in your actual javascript file, which you can use to wrap your code around.
function start() {
/* your code */
}
The reason jQuery couldn't be found the first times is because your browser caches the jQuery when it is fully loaded. It has to load the entire file the first time you actually visit or force-reload the page.
When you use async on a script tag, the script can execute in any order, at any point during the page load, which is why your scripts work only sometimes. You trade away knowing the order of execution for slightly faster page loads. This usually requires that the scripts you load do not depend on each other or an elaborate loading scheme - usually using one callback function that runs without async and invokes your code when dependencies report they're available.
You should consider if async is really the right option for your setup.
Related
This question already has answers here:
Unobtrusive JavaScript: <script> at the top or the bottom of the HTML code?
(7 answers)
Closed 8 years ago.
I have listen a lot that we should always load the java script at the end of the page why we should do that. If i write the java script at starting of the page how it will make the difference?
If you write javascript at the start of the page, than you'll not be able to access the DOM elements, directly.
However when you use it at bottom, all the elements will have been rendered and you can use them.
In the first case, you would need something like this:
window.onload = function(){
document.getElementById('id');
}
But in the second case, you need just:
document.getElementById('id');
Also, if you have scripts at the start of the page, it will block the UI from rendering.
If you're using JS to manipulate the DOM, you'll want the page to be loaded before the script is run - usually this means placing the script after the page content.
However, if the Javascript is in response to say an onClick event, you shouldn't need to put it at the base of the page.
This question already has answers here:
document.ready inside body tag
(2 answers)
Closed 9 years ago.
We often read here and there, that we must place our js code either on the page head section or before (sorry) the end body tag. Discussions about this aside, I'm just looking to know what are the reading order for such things by the browsers (taking that they do act as equals here):
Can we place:
$(document).ready(function(){
No matter where on the page structure, because we are using $(document).ready or should we still place it on the head section ?
Can anyone please clarify this.
If my question isn't clear, I can rephrase.
You can place a script anywhere in the document. Best practice usually advises placing scripts in the footer for page load performance concerns. Further, best practice usually advises placing the scripts together for ease of maintenance.
However, per the spec, there is no restriction on where in the document you place a script tag. You may place them together in the header, at the bottom of the body, sprinkled all over the document, or any combination thereof.
The use of the jQuery construct $(document).ready has the same result regardless of where it is placed within the document. The key is to understand the functionality behind this construct:
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received.
So, ready is similar to document.onload, but not the same. It doesn't matter where the code is, if you execute it when document.onload is fired or when jQuery fires ready. Code's placement in a document is only significant if it is NOT wrapped by some event handler/listener.
The only restriction on the location on $(document).ready is that it cannot happen before you include the jQuery library. $(document).ready is using jQuery, so if jQuery doesn't exist.... you can't use it.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
alert('executed as soon as it is reached (as the document is downloaded)');
$(document).ready(function () { alert('on jQuery ready'); });
</script>
</head>
<body onload="alert('executed on document.onload event');">
<script>
alert('executed as soon as it is reached (as the document is downloaded)');
$(document).ready(function () { alert('on jQuery ready'); });
</script>
</body>
</html>
Documentation
SCRIPT specification at W3 - http://www.w3.org/TR/html401/interact/scripts.html
script (html 5) specification at W3 - http://www.w3.org/TR/html-markup/script.html
Placing Javascript in your pages at quirksmode - http://www.quirksmode.org/js/placejs.html
Jquery ready - http://api.jquery.com/ready/
AFAIK, $(document).ready event gets raised after DOM is completely loaded so it doesn't matter where you place it.
But they say to write the script at end of the body because page will show up to the end user instantly and javascript will continue to run as background process.
The browser executes the script from the top to the bottom, so the srcipt in the head section will execute before the script in the body. I prefer to put the script undernith the html code, but generally it desn't matter much if you vait for the page to fuly load.
The document ready function will wait until the DOM is loaded before running. So technically it doesn't matter where you put it. Many people like putting script in the head, because it makes sure the script is read before the page is loaded. Other people like putting it at the very end (just before the end body tag) so that all of the elements of the page are loaded before the script reads them. But since you're waiting for the DOM to load anyway, it doesn't matter.
If you have a small function, then I would just put the document ready function in the head tags.
As far as i know, the BKM is to place it in the footer (although mostly developers tend to place it in the head tag).
Main reason - most of the document DOM is rendered to the browser prior to loading JS.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Javascript on the bottom of the page?
I saw a comment in some twitter bootstrap example. It says
JavaScript placed at the end of the document so the pages load faster
Is this true?? If yes then How it works??
There are a number of advantages
There’s no need to have a check if the DOM is loaded, since by having
the scripts at the end, you know for sure it is.
A JavaScript script
file has to be loaded completely before a web browser even begins on
the next JavaScript file. The effect of this, if the JavaScript files
are included at the top of the document, is that it will be a visual
delay before the end user sees the actual page. This is completely
avoided if you include the JavaScript files at the end of the
document.
There are some limitations as well
While including the JavaScript files at the bottom helps us around the
problem of delaying the page rendering, thus giving the impression
that each page in the web site loads faster, it does have a drawback.
If the page is visible to the end user, but the JavaScript files haven’t finished loading yet, no events have been applied to the
elements yet (because everyone uses an unobtrusive approach, right?)
and the user might start clicking around and not getting the expected
results.
If you have proper fallbacks, e.g. a link element which gets content via AJAX if JavaScript is supported and the proper event has been
applied, otherwise it’s a normal link leading to another page, then
the problem isn’t that bad. Still somewhat annoying, though.
Useful Article Here
If the browser encounters a <script> tag, the HTMLRenderer will by default stop and the ECMAscript parser will do its job. The HTMLRenderer will not continue untill all the Javascript code was completely evalutated.
So, if you have many <script> tags and lots of Javascript code in your "upper" HTML code, a viewer of your site might realize a slow'ish loading process.
There are several ways to avoid this issues. The first is, as you mentioned, by just placing all the Javascript code and <script> tags at the very bottom of the <body> element. That ensures that at least all the HTML markup and Stylesheet definitions were fully loaded.
Another options are tag names for the <script> element itself. Such as async and defer will indicate to the Browser / JS Parser that this fill is not required to get loaded and evaluated immediately. For instance
<script async defer src="/foo/bar.js"></script>
The HTML Renderer will realize the tag and store it into a queue, but it will not directly stop and evaluate.
Most browsers execute JavaScript and load the page using the same thread. Hence while JavaScript is executing the page cannot load. Thus if you page contains lots of images or embedded content these assets will not start loading until the JavaScript completes execution.
This is the reason it's advised to put long running synchronous code at the end of the document, or defer it to load when the page loads or the DOM content loads. However modern browsers usually notify the user about long running blocking scripts and allow them to terminate the script if desired.
As important as placing them at the end of the page, is specifying them as async using the HTML5 async attribute. This will ensure that the parser does not stop and parse them but rather continues with the page loading flow and downloads/parses the JS in parallel.
http://davidwalsh.name/html5-async
The logic behind that concept is that since the browser renders your code on the fly, by placing all the html elements before the scripts, it could theoretically load faster than if you had the scripts first, assuming you had an astronomical amount of scripts to deal with.
In practise however no one should ever encounter a situation that would require so much script time that it would affect the load time of a website over more pressing bottlenecks as D/L bandwidth.
Interesting problem here from some inherited code I recently looked at. I'm trying to add a compression module to a project. It is loading all the JS and CSS files, combining them, minifying them, and compressing them. I've tried a number of solutions, but all of them have one fatal problem.
I have some javascript that is being loaded via Page.ClientScript.RegisterClientScriptBlock in the PreRender of the MasterPage. The compression module is loading as a Script Tag link in the MasterPage, but when I run the page... the code from the PreRender is lopped on top and is giving me a '$ is undefined' error, telling me jQuery isn't loaded yet.
Furthermore, I can't seem to get past the same problem when it comes to inline javascript on content pages.
Any ideas as to what is causing this? Enlighten me as I have no clue.
If have done this before with RegisterStartupScript (instead of RegisterClientScriptBlock) and called the $(document).ready(function() from WITHIN that script.
If the script tag link that eventually expands out to jquery is not in the head, but in the body of the page, then $ will be undefined when the script block executes, unless it is included in the html before the opening <form /> tag in the rendered html, which I understand is where RegisterClientScriptBlock spits out its script (just after that opening tag).
If this is not the case, and the joined/minified script is in the head, then I'd use a browser debugger such as Firebug or IE Dev Tools to verify that the jquery script is being correctly included in your combined script.
I know this answer is late to the party, but try calling ClientScript.RegisterClientScriptBlock in your OnPreRenderComplete (rather than OnPreRender) handler. This inserts the code later in the page rendering process.
All your jQuery code should be written inside the DOM-ready function:
$(function() {
// your code here
});
indipendently from where you place it in the page, 'cause the jQuery() function isn't avalaible before.
If I keep JavaScript code at bottom or keep JavaScript code in <head> inside document.ready, are both same thing?
I'm confused between these two methodologies, http://api.jquery.com/ready/ and http://developer.yahoo.com/performance/rules.html#js_bottom.
Is there any benefit to putting JavaScript code at bottom (just before </body>) even if I keep the code inside.
$(document).ready(function() {
// code here
});
As JavaScript is attached in
<head>
<script type="text/javascript" src="example.js"></script>
</head>
In General, your should put your Javascript files at the bottom of your HTML file.
That is even more important if you're using "classical" <script> tag files. Most browsers (even modern ones) will block the UI thread and therefore the render process of your HTML markup while loading & executing javascript.
That in turn means, if you're loading a decent amount of Javascript at the top of your page, the user will expire a "slow" loading of your page, because he will see your whole markup after all your script has been loaded and executed.
To make this problem even worse, most browsers will not download javascript files in a parallel mode. If you have a something like this:
<script type="javascript" src="/path/file1.js"></script>
<script type="javascript" src="/path/file2.js"></script>
<script type="javascript" src="/path/file3.js"></script>
your browser will
load file1.js
execute file1.js
load file2.js
execute file2.js
load file3.js
execute file3.js
and while doing so, both the UI thread and the rendering process are blocked.
Some browsers like Chrome finally started to load script files in parallel mode which makes that whole problem a little bit less of an issue.
Another way to "workaround" that problem is to use dynamic script tag insertion. Which basically means you only load one javascript file over a <script> tag. This (loader) script then dynamically creates <script> tags and inserts them into your markup. That works asyncronously and is way better (in terms of performance).
They will load all the same in terms of you being able to access the code.
The differences are in the perceived speed of loading of the page. If the javascript is last it will not block any CSS that is trying to be downloaded, which should always be at the top, and will not block any images that need to be downloaded.
Browsers only ask for items as they find them in the HTML but they only have a limited amount of download streams (~10 in modern browsers) so if you doing a lot of requests for images/css and for JS something is going to lose and the perceived speed/ user experience of the page load of your page will take a hit.
They are not the same thing as the ready event is fired when the DOM tree has been built, while scripts at the end of the page may actually execute afterward.
Either way, they're both safe entry points for your app's execution.
The Yahoo! Developer site is saying that if you put JavaScript at the bottom of the page, it won't block loading of other resources by the browser. This will make the page's initial load quicker.
jQuery is specifying a function to load when the entire page has loaded.
If you have a function which executes on page load, it won't matter whether you include it in <head> or at the bottom of the page, it will be executed at the same time.
It's important to consider what the JavaScript is actually doing on your page when deciding where to put it. In most cases, the time it takes to load and run JavaScript makes placing it at the end of the page more logical. However, if the page rendering itself depends on Ajax calls or similar, this might not be the case.
Here's a good read on the subject of document.ready() not being appropriate for all JS.
Position of <script> tag don't involve your script if you use document.ready.
It seems JavaScript is charged faster when placed before </body> but I'm not sure.
Even with the script at the bottom of the HTML document, the DOM may not be fully loaded. All closed elements above the script will typically be ready, a DOM ready event may be necessary in corner cases.