Where to insert JavaScript Libraries and CSS in my HTML code? - javascript

I am little new to web development and when I was searching internet about other topics, I have seen many people has put popular JS Libraries in Different Places of their websites.
eg: Inserting JS Libraries on the Very Beginning or Start of the <head> </head> section. (Before loading any JS Code or a CSS File)
eg: Inserting JS Libraries on the End of the <head> </head> section. (After loading all JS Codes and CSS Files)
eg: Inserting JS Libraries on the End of the <body> </body> section. (After loading all JS Codes, Texts, Images, Videos, CSS Files etc...)
So my question is this.
What is the best practice for inserting (where) following JS Libraries, Plugins and CSS Style Sheets to a web page for the most faster loading times and other advantages? - Please mention the reason -
JQuery and it's Plugins
Bootstrap 3.js
Modernizr.js
Angular.js
And another widely used JS Libraries which I couldn't mention here...
Normalize.css
reset.css
bootstrap.css + more
Thank You..!

There is no so called "standard" method. The choice of where to put the lines boils down to one question: When will I need the library?
You see, web files loads line by line, let's take the following as an example of what I mean:
<script>
document.getElementById("target").innerHTML = "changed"
</script>
<p id="target">unchanged</p>
#target isn't altered because the script was loaded before the element did. Web files loads procedurally. When the line of JavaScript is loaded. It is executed immediately, but the target element isn't. So it couldn't change the element.
Even with jQuery, there is the same problem:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$("#target").text("changed");
</script>
<p id="target">unchanged</p>
Therefore, we often use $(function(){}).
Back to the loading problem
People who put their <script> tags or <link> tags in the body (in front) or in the head, wanted to execute the script immediately, sometimes they won't use $(function()) or document.onload
People who put their <script> tags or <link> tags in the body (in the end) wanted to ensure all elements are loaded then execute the script or load CSS.
Conclusion
You should load independent resources such as jQuery first, then load dependent resources such as jQuery plugins. Then you try to decide when you want the resources to start loading, then put the lines in places.
You should put CSS links in the <head> tag because you don't want visitors seeing unstyled content before loading the CSS files.
If you can't decide or don't care about the time, put every <script> and <style> tags in the <head>.
Here is another post you might be interested in: Load and execution sequence of a web page?

CSS can added inside header tag & but put all JS Libraries and custom files just before closing closing body tag
<body>
//other tags
<script> All Scripts here </script>
</body>
By doing so you wont have to check if DOM content has loaded.
It decrease page loading time.Otherwise a js need to be completely loaded before DOM loading.
It also makes sure that all events are attached properly to DOM element.
I think this address all your concern specially the third one

CSS Sheets go in the < head >. The order of the CSS files matter so libraries should be put in first then you can put in the specific ones you have.
Javascript links go in the < body > but place them at the very end. That way your HTML content loads first then the JS loads and it will recognize all your selections. It is more efficient to do it this way.

The most important thing to note when placing your css and script tags is that the order you place them determines the order they are loaded in and if style or code is loaded later it over writes the code written before. So if you have css styling that assigns different styles to the same attributes of the same element then it is the one loaded later that takes effect. And with script tags it's important to remember that for dependency reasons. You should load the dependencies first so that they are there for the other scripts to use. Aside from that normally css tags are in the head and script tags at the bottom of your body element

Related

How should I place my scripts in my html files?

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.

How to make sure that all css and js files in web page or android app are loaded?

I have developed a mobile application which loads 3 css and 7 javascript files. Problem is if the wifi signal is very slow, HTML loads before all javascript and stylesheets are loaded. Since stylesheet is not loaded, HTML looks disturbed and after few seconds (i guess after css and js are loaded properly), HTML structure automatically take correct format but I dont want to show the disturbed format and to do that I need to make sure that all js files are loaded first then only HTML should display.
If you have any idea how can this be achieved ?
You can do using Cache manifests. Read these resources:
http://appcachefacts.info/
http://en.wikipedia.org/wiki/Cache_manifest_in_HTML5
https://developer.mozilla.org/en/docs/HTML/Using_the_application_cache
Alternatively - ensure your resources are loaded before the body by placing them in the right place (head tag).
You should link to your external css stylesheet at the top of your webpage in the header like this:
<link rel="stylesheet" type="text/css" href="http://whiterootmedia.com/css/example.css" />
or insert your <style> element in the header. Likewise this should be done for your JavaScript if it effects your initial layout. Keep in mind that if you are using an external JS file, the browser will stop rendering your page at the point in your code where your external JavaScript file is referenced, to load that external JavaScript file. If you're using a lot of JavaScript, place it at the bottom of your page (contrary to what most people do) or use an onload() function.
The webpage is loaded top-to-bottom, so the problems you're having should be related to the order of your css (most likely).

jQuery in CSS style sheet

I’m working on making my web site fade in and out every time I click a link to another page. I need to use jQuery to do this. Do I need to put the jQuery code on every page or can I write jQuery into the CSS Stylesheet? If so, how do I format the CSS Stylesheet to accept jQuery?
I’m experimenting with the code from this forum post: Fade Out between pages – CSS-Tricks
Edit to question based on comments
So, I now know that I can’t put JavaScript in CSS file. What’s the best way to put JavaScript code that applies to all pages in a site? I want to write this transition code and then not have to write/edit it into every page.
Save the JavaScript in a file with the extension .js, for example main.js. Then give it a public URL, in a similar way that your CSS files are accessible from a URL. An example URL: http://example.com/js/main.js. You might do that by putting it in a js folder in your public_html folder on your server – it depends on your server.
Then, near the end of each page’s HTML, right above </body>, add this HTML tag:
<script src="/js/main.js"></script>
The script tag with a src attribute will load the JavaScript at the given URL and then run it immediately.
I recommend putting it at the end of your <body> element and not inside the <head> because the script prevents the rest of the page from loading and displaying to the user while the script runs. If you make the script run only at the very end of the page, the page is already loaded and the user can see all of its content.
you need to do a $.fadeout on the window.beforeunload event, bye
PD: in a js file, not in a stylesheet, you can´t use JS in a stylesheet. bye.

How can I load js files in specific pages using jQueryMobile?

It's a known fact that jQueryMobile loads pages with ajax and is not including in DOM the header content in every pages.
I need to load a custom js file in some pages, how can I achieve this? Until now I have placed the .js files in the body, but there are some problems with the code there too so it's not a good workaround. Until I can find a solution I will use the rel="external" workaround, but I really need to find an answer to my question.
You could try including the custom script within the data-role="page" div in pages where you want to use those javascript.
From JQM docs:
Another approach for page-specific scripting would be to include
scripts at the end of the body element. If you include your custom
scripting this way, be aware that these scripts will execute when that
page is loaded via Ajax or regular HTTP, so if these scripts are the
same on every page, you'll likely run into problems. If you're
including scripts this way, we'd recommend enclosing your page content
in a data-role="page" element, and placing scripts that are referenced
on every page outside of that element. Scripts that are unique to that
page can be placed in that element, to ensure that they execute when
the page is fetched via Ajax.
You could use some javascript to dynamically add the js file to the DOM.
This is demoed here: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

Move jQuery to the end of body tag?

My friend read an article which mentioned that moving all JavaScript files to the end of the closing body tag (</body>), will improve the performance of a web page.
I have moved all JS files to the end except the JQuery and the JS files which are attaching event to an element on page, like below;
$(document).ready(function(){
//submit data
$("#create_video").click(function(){ //... });
});
but he's saying to move the jQuery library file to the end of body tag.
I don't think it is possible, because I am attaching many events to page elements on load using jQuery selectors, and to use jQuery selectors it is must to load jQuery library first.
Is it possible to move JQuery library file to the end of page right before closing body tag (</body>) ??
Thanks
It's standard practice to move all your js includes to the bottom of your page. This is because when a browser loads script, it does not spawn a new thread to do so, so basically the browser will wait until it has loaded the script before it proceeds to the next line.
What this means for your users is that they will see a blank screen. Much better to have them see the full(ish) page as then it doesn't look like it has stalled.
The $(document).ready function says not to run until the DOM has finished being instantiated - so moving it to after body is okay so long as the JQuery library is loaded first. Unconventional and some assumptions may not be correct anymore but okay.
Just take in account that the jQuery JavaScript file must be loaded before any call to the $(...) function.
Use a "Dom Ready Queue" to collect functions to be executed once jQuery is loaded and the DOM is ready.
Example:
<html>
<head>
<script type="text/javascript">
var domReadyQueue = [];
</script>
</head>
<body>
...
<div class="foo"></div>
<script type="text/javascript">
domReadyQueue.push(function($){
$('.foo').doSomething();
})
</script>
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function(){
while (domReadyQueue.length) {
domReadyQueue.shift()(jQuery);
}
});
</script>
</body>
</html>
The reason that article asked you to move scripts to the bottom, is to allow other artifacts to get downloaded first. (css & images, which will speed up apparent rendering times)
This is because HTTP 1.1 recommends only downloading 2 items per hostname. And you would definitely want your css file to be one of the first files downloaded, rather than javascript which could make the site appear to render slower (just by the fact that the browser hasn't got the css file yet and isn't sure what it should do with the html)
But if you used google to host your jQuery then that would download in parallel and negates any reason for moving it to the bottom of your pages.
Alternatively, you could set up a second hostname to host static content (such as css/scripts/images).
But google have already done the hard work for you, so it makes sense to use it if it suits. :-)
Q - Why do I often see JavaScript
written/included before the closing
body element in an (x)HTML document?
A - DOM elements can not be accessed
by JavaScript until the browser has
loaded the HTML elements into the DOM.
By placing JavaScript at the end of an
(x)HTML document (before the closing
body element), you will ensure that
the script is called as soon as the
DOM is constructed/loaded and ready
for manipulation. An advantage of this
approach is that JavaScript code is
executed right after the DOM is
constructed and possibly before the
onload event would fire.
JavaScript beginners get tripped up by
this constantly by placing code that
manipulates the DOM in the header
element of an (x)HTML document. This
causes an error because the DOM has
not yet been constructed and thus is
not yet accessible to JavaScript that
traverses/manipulates the DOM.
From JavaScript Execution & Onload Techniques in Web Browsers
Use unobtrusive javascript (adding event listeners to elements instead of onclik ="..." etc).
Put all your .js files at the bottom of the body tag, with the main library (jQuery in this case) placed first, and everything will be fine. You can use a bundler like bundle fu
You will see a big performance boost of loading your page.

Categories

Resources