I am aware its a best practice to put your javascript/jquery at the bottom of the page.
But how exactly can i achieve this "best practice"?
In my current webproject (MVC4) I have placed my javascript at the bottom.
But i am unable to make anything work unless i put my javascript in the header(which is considered bad practice?).
<body>
<div id="container">
<div id="header">
</div>
<div id="content">
<!--js function that calls upon jQuery (slider) -->
</div>
</div>
<!--Javascript declaration-->
</body>
For example:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/slider.js"></script>
The function slider.js requires jQuery to make my slider work.
Is there a way to keep all my javascript files (including jQuery) at the bottom and load jQuery (or a other function / library) if a function needs to access it?
Update
The problem seems to be with the MVC bundles.
When i put the javascript files in the normal syntax at the bottom everything works.
Are separate bundles required? Not sure in what kind of order MVC loads the bundles.
When applying this kind of bundle (jquery first followed by the js function) the order of exection is wrong.
Because of this i cannot really see the advantage of bundles, someone care to explain?
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-1.7.1.js",
"~/Scripts/js/slider.js"));
Thanks.
The reason why this is good is because browsers load scrips synchronously with the web page. So if you put them at the top, loading big scrips will stall the content loading. If you place it at the bottom before the close of the body tag, the content will load first, thus making the page pop up much faster without the stall of scripts.
To fix your problem, wrap all of your executing code in a document.ready, or the jquery equivalent:
$(function(){
//your code here
})
If jQuery is not loaded yet, you can check with a console.log:
if(!window.jQuery)
{
console.log("problem");
}
You haven't provided much information here, which makes it hard to debug. All I can do is give you the steps to do it. You just have to make sure that jQuery is loaded before any other script runs on the page.
Do you have inline script tags in your page?
You should be able to put those at the bottom as long as the jQuery import is before your script. Do you have other javascript in your page which depends on either of those scripts?
Related
We're using a webprogram that uses ajax and jquery and the like (Netsuite). I want to change something on a page and have tried to use document.ready and window.load to get an external script loaded on the page. I've tried to load the external script in the head and body.. but the contents aren't written. The external file looks for a specific div id and then prepends some code to that. It never works, because the page itself loads dynamically and the div I'm looking for loads when the rest of the page is done. So window.load, etc. never work...
At last I'm in the program itself that loads parts and pieces and am trying to simply write the external script file in there. Now this time the external file has a simple document.write in it, so it's straightforward. In other words, the script is in the middle of html code in the body of the page. (I know this is a terrible way of doing it, but I've got to try something to get this to work....)
According to firebug, it writes the external file where it should be (check!) and firebug shows me the contents of that file (check!), but ... it never 'writes' it onto the page...
The file just contains this:
document.write('<div id="shpblk" style="border:2px solid #ffa500;border-radius:7px;color:#000066;margin:5px;padding:5px;text-align:left;"><img border="0" width="12" height="12" src="/images/icons/store/icon_exclamation2c.gif">Hazardous conditions blahblah... Potential delays and disruptions can be anticipated.</div>');
What am I missing?
Edit: some more clarification is necessary...:
Situation: I have to be able to put a piece of html on the page every now and then that creates a message.
Environment: What I have is a page that loads a header and footer first (which are set up in separate files) and then it takes a second or so to load the rest of the page. From what I understand, this "rest of the page" is written in a certain code, similar to javascript/jquery.
What I CAN do is: edit the files for the header and footer and put javascript in there to make modifications to the rest of the page. I can access some of the files that contain parts and pieces of the "rest of the page", but this is a huge pile of spaghetti.
What I've tried:
Since I want to be flexible with the html that I need to put into the page, I preferably would like to create a piece of javascript or html or whatever on another site and have the "environment" pick up that code. I can do this with javascript or iframe. But since it's a secure area (https), I thought it would be best to use a javascript file instead of an iframe. So....
I created the javascript file and tried it out in a normal environment where I knew for sure it would work.. and it works like a charm. But when I tried this in the before mentioned "environment", I am running against a wall...
The javascript file has document.ready jquery statement in it and it would prepend the html div to an existing div on the page.
This way it would load the page and write the page.. easy as pie.
However.. since the header and footer load first (which includes the external script file), and then the rest of the page, SOMEHOW the div where the script checks for DOES NOT EXIST YET. So I tried window.load instead of document.ready. Same result.
Now, it WOULD appear ONLY when I refresh the page. So there may be a way to have it refresh the page, but I only want this as the absolute last attempt.
So then I tried to see if I could go around this by changing the script so that, instead of using a document.ready it would just do a simple javascript document.write statement.
Then I call the script in the middle of the body of the page (I put it in one of the files that load in the middle of the page). I know this is not something I would do normally, but wanted to try it out anyway. So.... I would have something like this:
<div id="block1">
<div id="block2">stuff here<div>
<script type="text/javascript" src="https://someotherdomain.com/include.js" ></script>
<div id="block3">stuff here<div>
<div id="block4">stuff here<div>
</div>
Now when I run this, I do not get any errors, but nothing is being done with the contents of that js file. In firebug it shows me the contents of that file though.. so I assume it's being read.
But I have no idea why it doesn't run.
Again.. back to 'normal' practices: I've tried window.load, because this would run the statement after the page loads, HOWEVER.. like I said before, I have the feeling it builds the contents of the (middle of the) page through this somehow and my script runs before this; it cannot find the div (block3) where it would prepend to. Whenever I stop running the page at my script, the div it's depending on doesn't exist yet...
I hope this made sense...
Solution
For the external script file to work as expected, OP will need to load it using an asynchronous script tag like this:
<script type="text/javascript" src="include.js" ></script>
Yet, the file contains a document.write() statement, which is generally something to avoid. A better alternative would be remove document.write() from the file and save it as a plain HTML file. This could then be safely loaded using using jQuery:
$("#include1").load("include.html");
( Requires adding a target DIV to the page where the content should load. )
DETAILS
The question doesn't tell us how the external file is included on the page. And without that information it's difficult to understand the problem or provide a solution ... which is probably why this question has gone unanswered.
Yet, let's assume the the script is being injected into the page on the client side using JavaScript or jQuery. And if that's true then it will fail if not done the correct way.
Let's look at some ways we might add the script to the page:
These script tags will all fail because the file contains a document.write statement and the script is loaded asynchronously.
<script type="text/javascript" src="include.js" async ></script>
<script type="text/javascript" src="include.js" defer ></script>
<script type="text/javascript" src="include.js" async defer ></script>
The browser does load the file, but reports:
Failed to execute 'write' on 'Document': It isn't possible to write
into a document from an asynchronously-loaded external script unless
it is explicitly opened.
This jQuery sort of works. It loads the script, but the document.write implicitly calls document.open, which erases the original content of the page. That's probably not what OP wants.
$.getScript('include.js');
This synchronous method works so long as the document.write is executed on load, i.e., is not inside function called later. So this is a possible solution for OP.
<script type="text/javascript" src="include.js" ></script>
How should I place my scripts in my html files? Is there any difference to the browser?
To place all <script> elements before the <body>
To place all <script> elements to the top of the <body>
To place all <script> elements to the end of the <body>
To place all <script> elements after the </body>
Because I think I have used all 4 variants before, but I think there should be some consistency of the </script> elements placement.
As a rule of thumb: Script tags should go at the bottom, unless they need to be higher up.
That's because they block the rest of the page from rendering until that script is done executing.
I think google recommends putting their analytics tracking script in the head. That's so if people leave your site before it's done loading, they can still track the visit.
you can put almost everywhere, but the main ways to do it is by placing it in the <head> or after the body part. Place it after all body of the document will speed up the loading of your page
I think it depends on usage of the script files.
Higher in the document loads earlier but do you need them as soon as possible?
Google advises against loading javascript in the head (https://developers.google.com/speed/docs/insights/BlockingJS).
But some tracking code (and google analytics also: https://support.google.com/analytics/answer/1008080?hl=en) need to be placed in the head section of the document for proper collection of data.
Also javascript may be used for content loading etc. and therefore should be placed as high as possible.
It is considered to be a good practice to put all synchronously (the normal ones) loaded scripts to the bottom of <body>, since they block rendering of rest of the page.
However, asynchronously loaded scripts and trackers (i.e. Google Analytics) can be placed wherever, since they are downloaded and executed parallelly and they should fire off as soon as possible.
As for the synchronous scripts, the order is determined by dependencies, ususally first go basic frameworks (i.e. jQuery), then its modules or plugins, then your own "inicialization" code.
Usually is necessary to execute the script code after the page is completely loaded. In this case, the default option is right before the </body> tag.
There are some cases you need to include scripts before the page loads inside head tag.
I'm looking for a way to load jquery after the page is fully loaded.
well there are lots of questions and answers about it in here, but all describe how to run a script that needs jquery after either page or jquery fully loaded.
What I'm looking for is to load the page and then call jquery and after the jquery is loaded call the functions. something like:
document.onload=function(){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
//Here I need an event to know that jquery is
//loaded to run stuff that needs jquery
}
Try this:
$(document).ready(function() {
// When the document is ready
// Do something
});
You can also use:
$(window).bind("load", function() {
// Your code here.
});
For your problem, the solution might be to attach CDN hosted by google with certain library:
https://developers.google.com/speed/libraries/devguide
Also, you can add this at the bottom of page (just before </body>):
<script type="text/javascript">
(function() {
var script = document.createElement('script')
script.setAttribute("type", "text/javascript")
script.setAttribute("src", "https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js")
document.getElementsByTagName("head")[0].appendChild(script)
})();
</script>
However, this is risky in my opinion. You have an asynchronous call for jquery, thus your jquery has to wait until it loads (ie. $(document).ready won't work in this case). So my answer would be: use a CDN like google suggests; put your javascript on the bottom just before </body>; and, ignore flags from profilers.
It is advised to load your scripts at the bottom of your <body> block to speed up the page load, like this:
<body>
<!-- your content -->
<!-- your scripts -->
<script src=".."></script>
</body>
</html>
You can either use .onload function. It runs a function when the page is fully loaded including graphics.
window.onload=function(){
// Run code
};
Or another way is : Include scripts at the bottom of your page.
You can try using your function and using a timeout waiting until the jQuery object is loaded
Code:
document.onload=function(){
var fileref=document.createElement('script');
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", 'http://code.jquery.com/jquery-1.7.2.min.js');
document.getElementsByTagName("head")[0].appendChild(fileref);
waitForjQuery();
}
function waitForjQuery() {
if (typeof jQuery != 'undefined') {
// do some stuff
} else {
window.setTimeout(function () { waitForjQuery(); }, 100);
}
}
My guess is that you load jQuery in the <head> section of your page. While this is not harmful, it slows down page load. Try using this pattern to speed up initial loading time of the DOM-Tree:
<!doctype html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="">
</head>
<body>
<!-- PAGE CONTENT -->
<!-- JS -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script>
$(function() {
$('body').append('<p>I can happily use jQuery</p>');
});
</script>
</body>
</html>
Just add your scripts at the end of your <body>tag.
There are some scripts that need to be in the head due to practical reasons, the most prominent library being Modernizr
if you can load jQuery from your own server, then you can append this to your jQuery file:
jQuery(document).trigger('jquery.loaded');
then you can bind to that triggered event.
Include your scripts at the bottom of the page before closing body tag.
More info HERE.
If you're trying to avoid loading jquery until your content has been loaded, the best way is to simply put the reference to it in the bottom of your page, like many other answers have said.
General tips on Jquery usage:
Use a CDN. This way, your site can use the cached version a user likely has on their computer. The // at the beginning allows it to be called (and use the same resource) whether it's http or https. Example:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Using a CDN has a couple of big benefits: it makes it more likely that users have it cached from another site, so there will be no download (and no render-blocking). Further, CDNs use the closest, fastest connection available, meaning that if they do need to load it, it will probably be faster than connecting to your server. More info from Google.
Put scripts at the bottom. Move as much of your js to the bottom of the page as possible. I use php to include a file with all my JS resources below the footer.
If you're using a template system, you may need to have javascript spread throughout the html output. If you're using jquery in scripts that get called as the page renders, this will cause errors. To have your scripts wait until jquery is loaded, put them into
window.onload() = function () { //... your js that isn't called by user interaction ... }
This will prevent errors but still run before user interaction and without timers.
Of course, if jquery is cached, it won't matter too much where you put it, except to page speed tools that will tell you you're blocking rendering.
I have asked this question more than 6 years ago, and any answers I got had some flaws. Later I myself worked out a solution that I have been using for years since then. Now that I came across my own question again and I saw that it has many views, I'd like to share it because I think it may help others.
This problem mainly occurs on Master-Detail type of pages (can be old .master and .aspx pages) or (layout and views in asp.net) or any similar situation maybe on other web development languages, however always there is a master-detail pattern involved.
For the solution, I just add an array at the beginning of my page:
<script>var after = [];</script>
any function that requires jQuery or any other script that would run after this section, instead of running it, I just push it to this array:
after.push(function(){
// code that requires scripts that will load later,
//might be for example a jQuery selector or ...
});
and then at the very end of the page, right before closing the body tag (of course scripts are loaded by now) I run all the functions inside the (here named) after array:
<script>for(var i=0;i<after.length;i++)after[i]();</script>
</body>
I find this way very easy, simple and flawless.
The following link http://developer.yahoo.com/performance/rules.html#js_bottom says
"Put Scripts at the Bottom" for Speeding Up Your Web Site. Lets say I have added them at bottom
<html>
<head></head>
<body>
...
...
...
html
....
<script src="script1"/>
<script src="script2"/>
<script src="script3"/>
</body>
</html>
Now if I have the requirement to access some function of those js files somewhere in the middle of html, how would I do that? Let's say the code is like this
<html>
<head></head>
<body>
...
...
...
html
.....
<script>
$('a.test').modal('show);
</script>
....
<script src="script1"/>
<script src="script2"/>
<script src="script3"/>
</body>
</html>
Above "$", "modal" etc are the part of js libraries attached at the bottom of the page. How will I detect the completion of bottom scripts and fire the code written in script tag (
$('a.test').modal('show);
)
To execute a script you have to make sure you have to provided all the necessary dependencies for that script. Hence, you have two options:
Put necessary script references before the particular script
Put the script at the bottom of the page.
Nothing is set in stone and the real solution depends on your particular problem.
Its a general good coding practice to keep all scripts at one portion of html.
Having said that, i would suggest the same thing, to have maximum of script loading at the bottom, this helps in quick loading.
As far as dependencies go, if you script is dependent on something, try including it before it is called. Its basically iterative :)
You'll have to consider your design and what you want to do with your page.
Start with your hypothesis: Putting tags at the bottom speeds up your website.
Does it speed up your website? not really. So what does it do? The advantage of loading a script at the bottom of the DOM means that the DOM always gets loaded first.
The page is parsed from top to bottom, as soon as a script tag is encountered it gets executed. If the script tag has a link on it that script gets loaded synchronously, holding off rendering of the DOM.
If you absolutely need jQuery to do stuff in the middle of the page, load it on top. Is your webpage now slower? Yeah, it took a second to load jQuery. Were your audience impacted? By how much? a second?
Takeaways: Loading a script at the top is fine. Loading 10 scripts that end up being about 1 mbyte combined is not because it impacts UX.
As other people have mentioned, you can always selectors to manipulate that part of the code, no need to run a script in the middle of the page. It's a better practice to separate your UI from your code anyways.
You can defer execution of $ so that your code doesn't run until after your scripts have loaded.
http://www.mrclay.org/2010/11/14/using-jquery-before-its-loaded/
I've been trying to add JavaScript to my HTML/CSS, but been running around in circles.
My current set-up is where the html, CSS, and JavaScript files (2 files; my JavaScript code, and jQuery's code) are all separate, but linked to each other via the html page.
So here are my questions:
1) Do I put the link to the jQuery code within the html head? Or within my JavaScript code page?
2) Where does this code go? The html page, or my JavaScript page?
$(document).ready(function(){
//Code here
});
3) Above, by 'code here', they mean JavaScript code, right? Not my html code?
4) I've read about initializing JavaScript code at the bottom of an html page. From what I take though, I don't have to do that with jQuery's .ready function, right?
You should like to your JavaScript files either in the <head> or above the closing </body> tag.
The code can go anywhere really, but I would suggest an external JavaScript page.
Yes
This is correct.
When Javascript code is executing in your browser, all of your included Javascript files and any code you write in-between those "script" tags in the HTML document is going to be executed as though it were all part of one giant file (same namespace). So in some sense, it doesn't matter whether you write your code in the HTML document or whether you write it in an external file that you include - you're free to do either, and it will be executed the same. You can balance maintainability, reusability and convenience (think about what functions you write that you might want to reuse on other pages) and do whichever you feel is best.
To make this concrete - this is one valid way to write your Javascript, if you wanted to write the code inside your HTML file:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
alert('Document Ready!');
});
</script>
</head>
<body>
...
Here's the intro at the jQuery site, for reference:
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
Writing your Javascript code at the bottom of the HTML page was/is a technique for getting it to execute as soon as the document is loaded, which is unnecessary when using jQuery's '$(document).ready' (that's what it does - it abstracts the business of getting Javascript functions to execute on page load, and implements it in a cross-browser way).
See: Introducing $(document).ready() for more.
It doesn't really matter where you place your jQuery code. If you place it in the head tag, it'll automatically load everything. If you decide to place it all in an external JavaScript file, you need to link it with a <script type="text/javascript" src="my_file.js"></script> tag.
The 'code here' part is only for JavaScript. What the code is saying is that when the document is ready, run this function. The function can be whatever you like - whatever you put inside the function will run when the document is ready (i.e. when the webpage is called by the browser).
You don't need to insert it at the bottom of the HTML page - you can do it anywhere. People only insert it at the bottom to optimize their loading speed. It's nonessential.
$(document).ready(function(){
//Code here
});
goes in your javascript file. All javascript code that should be executed once the page has loaded goes where the //Code here comment is.
Perhaps a quick jQuery tutorial would be in order?
Or, you can put your script tag in the bottom of your body, and not have to use the $(document).ready() function.
Put in the head. This is the most stable way and it works. Some people may disagree and say it is slower, etc, but I have found this to always work.
Where you put your code is up to you. You can put in your head with a
<script>Code here</script>
or in a separate file and include it with
<script src="reftomyscript.js"></script>
Yes, put your javascript code in this, either in the head or in a separate file.
Yes, and see (1)