HTML / jQuery: How to properly include external jQuery file - javascript

I am new to JS and programming in general and hope someone can help me with this.
I am currently working on building a website where every page has its separate HTML / PHP file.
jQuery and my global / general JS functions are included in the footer of all these pages through a separate includes file "footer.php".
So far everything works as intended.
Now I have some pages that will use specific jQuery functions so I want to load the corresponding JS only if such a page is loaded.
To do this I saved the corresponding codes in separate JS files (e.g. nameOfExternalJsFile.js) and wrapped everything in there in the following:
$(document).ready(function(){
// ...
});
I then made the following updates to the corresponding PHP pages (example):
<head>
<?php
require_once("includes/header.php");
?>
<!-- here I want to include the specific jQuery functions -->
<script src="includes/js/nameOfExternalJsFile.js"></script>
</head>
<!-- ... -->
<!-- here I include the main JS functions -->
<?php require_once("includes/footer.php"); ?>
I have two concerns with this:
I am not sure if this is the right way of including such files since
I need to have them available on document ready.
I include my main JS in the footer since I was told this improves
performance but can I then include jQuery functions in the header at all ?
Can someone let me know if this is correct or if I should change anything here ?
Many thanks for any help with this.

Wrapping the functions in $(document).ready automatically takes care of this concern. From the JQuery documentation on document.ready.
A page can't be manipulated safely until the document is "ready."
jQuery detects this state of readiness for you. Code included inside
$( document ).ready() will only run once the page Document Object
Model (DOM) is ready for JavaScript code to execute.
Technically it doesn't matter whether you include the scripts in the header or the footer, as long you load JQuery first and your script second.
That said, it's generally recommended that both scripts go just before the closing body tag to increase performance as you suggested. There are some articles that discuss this like this post from performance expert Steve Souders and this guide from the Yahoo! Exceptional Performance team.

You should load the $(document).ready(...) stuff only after you have loaded jQuery, that is, in the footer file, after the jQuery <script> tag, like this :
<script src="includes/js/jQuery.min.js"></script>
<script src="includes/js/nameOfExternalJsFile.js"></script>

It`s good practise to locate all the JS files in the end of the body
<html>
<head></head>
<body>
... Some HTML
<script>SomeScripts</script>
</body>
</html>
</pre>
If you want to be sure that your external scripts are loaded after page load use:
$(function(){
/* Your code from the scripts */
});

You can change the content of footer.php to include /nameOfExternalJsFile.js manually at the bottom of the page. That´s the safest way to do it because you may load jquery before loading others scripts.

Related

Javascript not working on content pulled from another source

I'm pretty sure this is a dumb issue, but I searched and could not find a similar/equal scenario.
So, I have a main PHP page in which I include several Javascript files in the head section of the HTML. Then at some point I grab content (HTML + Javascript) from an outside source via file_get_contents and output it to the main page.
This new output will pick up the CSS styles from the main page normally, but any Javascript code that relies on the ones loaded at the main will not work. Even if I put the Javascript needed inside a document.ready in the main page, it will still not work.
Just to exemplify the code:
<html>
<head>
<link href="style.css" rel="stylesheet">
<script src="somejslib.js"></script>
</head>
<body>
Some HTML here generated by PHP
<?php
$content = file_get_contents('http://whatever/page');
echo $content;
?>
</body>
In the grabbed content I will have something like:
<div>
<form>
<input type="text" id="bla">
</form>
</div>
<script>$('#bla').datepicker({ somecodehere });</script>
The datepicker was included in the libs loaded in the main page, but will not work, no matter where I put this code.
Any hints?
P.S: the only way it DOES work is if I include - again - all the Javascript libs inside the new content, which of course is not a solution.
make sure you attach the listeners after the external content is loaded or use the on() event handler
http://api.jquery.com/on/
P.S. I now see your code is actually missing the document.ready and thus not waiting for the document to be loaded before executing. I'm not sure which of these applies to your actual code as you only posted an example. If you pull the content in via an ajax for example apply the first solution otherwise just wrap things up in a document ready
Solved.
Apparently it was my mistake all along. I was loading Jquery multiple times (different versions, also).
It seems that not all versions of jQuery can take care of this situation.

Where to load javascript scripts in html page

I am developing a jquery page and I think it is a little bit slow when you load it because I load all js files at the begining.
Would it be faster if I load just which I need at the begining and in each section, loads which I need?.
Now my webpage has all script calling in and after that, in all sections, home, page2, page3...
I structurated the webpage in one html file and I navigate to each section. Each section is like this:
<div data-role="page" id="secion2" data-theme="e">
<!--<script type='text/javascript' src='javascript/createFbAlbums.js'></script> -->
**LOAD SCRIPTS HERE**
<div data-theme = "f" data-role="header" data-id="fixedNav" data-position="fixed">
<h1>Page 2</h1>
</div> <!-- /header -->
<div data-role="content">
<ul data-role="listview" data-inset="true" class="managementEvents">
<li data-theme = "f">Page2</li>
<li data-theme = "f">Modify Exposiciones</li>
</ul>
</div> <!-- /content -->
Loading them in sections like the commented in this piece of code. Is this equal to load at the begining or not?
Or doing something like this inside javascript:
$(document).on("pageinit", '#section2', function(){
**LOAD HERE SCRIPTS**
Javascript code here doing everything in that page
});
I am a little bit lost because I don't know if this is ok or will break the page or will not speedup the loading.
The usual recommendation (for instance, in YUI's Best Practices for Speeding Up Your Web Site) is that unless you have a good reason to do something else, put your scripts at the very end of the page, just before the closing </body> tag:
<p>Content</p>
<div>More content</div>
<script src="/some/script.js"></script>
</body>
</html>
Side note: This also makes it essentially unnecessary to use jQuery's ready feature. If the script is at the very bottom of the page, all of the elements defined by the markup above it are available for scripting.
There's lots more useful advice in the page linked above. For example: To the extent possible, combine all of your scripts into a single file. (And make the file cachable, etc., etc.)
The downside: If you have content on your page that requires JavaScript to work correctly, the above means that the events related to that won't be hooked up right away. There can be a brief window of time between the content being available to the user, and the event handlers being registered. To deal with that, the concept of "progressive enhancement" comes into play: Make things work well without JavaScript, and then make them work better with JavaScript. Things that just can't work without JavaScript should be added by the JavaScript, or loaded initially-hidden and then shown by the JavaScript.
Whenever possible, JS files should be loaded at the bottom of the page. Prior to the closing body tag.
http://developer.yahoo.com/performance/rules.html#js_bottom
The reason is that JS files loading can block parallel downloads of other page assets. So they can cause a bottleneck.
In addition to that advice, since you're using jQuery, load jQuery from a CDN such as Google. There are a couple of benefits to doing that:
a popular CDN such as Google increases the odds that the end-user has already cached the JS library
it further reduces the parallel downloading bottleneck as it's another domain (the bottleneck is per-domain)
The recommendation is to put JavaScripts at the bottom of the page. This does not take into account dynamically loading your scripts, however, because there are differences in how browsers actually handle downloading external resources such as JS files between using tags and dynamically loading via JavaScript DOM manipulation.
Further Explanation
Browsers load HTML and any embedded resources synchronously as they parse the HTML. This means that as your page loads, when you have scripts up front, the loading of the page stops, the browser makes a request to download, then parse and evaluate/execute the JavaScript file, and then continues to load the rest of the HTML. It does this with each script.
Therefore, unless there are crucial elements that need to use some JS functions or variables during page load, and in some cases this is needed, it's better to load the JS at the bottom of the page because your page will render quicker. And in those crucial cases, only load enough JS to get the page load done as quick as possible.
As an interesting aside, loading JS files dynamically using JavaScript itself (i.e., dynamically inject script objects via javascript after page load), those scripts will load asynchronously and further improve page load times.
So to answer your question,
If you use the jQuery.ready() method of loading JS, it conforms to a best practice since the scripts will load after the page has already been loaded by the browser. This is in effect even better than placing tags at the bottom of the page.
$(document).ready(function () {
$.getScript( "yourScript.js" )
});
(Full example for jQuery getScript can be found here for more in-depth examples:
http://api.jquery.com/jquery.getscript/
You should always put your scripts at the bottom of your page before closing </body> tag
Refer here for more informations why you should do it.
Yes as everybody mentioned, it won't hurt putting the scripts at the bottom of page before </body> tag whereas it might create a problem sometime when you put the script in the head tag.
It would really be unnecessary to put your script at the end of your HTML if you use $(document).ready(function(){ then add your code, and close it with }) it will have the same effect, although both methods are considered good programming practice.

Should use Head.js or just minified scripts before </body> with scripts in the markup?

I have the optimisation problem — my site uses 2 (pretty large) javascript resources:
application.js (minimised jquery, jquery-ui, underscore-js and some shared scripts, 120KB total)
controller-specific file (some modules required for the page + interactions, 4KB total)
I have some scripts in the views that format/convert markup with JavaScript (dependable on both jQuery and my controller-specific JS code) so I need to wait either for $(document).ready or head.ready and it makes the part of website invisible to prevent the flash of unstyled content :(
Now my question comes: should I use head.js for it or just stick with the "before " scripts? Are there any smart ways to speed up page loading time in this case?
Update:
Here's the part of the code (see versusio.com for full code, landing page):
<html>
<head>
... usual stuff
<link (css stuff) />
<script src="head.js"></script>
<script>
// Here some global variables are set like cache keys, actual locale code etc., not dependable on jQuery or any other JS code from the JS assets
</script>
</head>
<body>
... page content
<div id="search">!-- here some code with the "display: none" style to prevent flash of unstyled content</div>
<script>
// Here is code that positions and processes some styles and adds some interactions to the #search div
Application.Position.In.Center($(#search), $(document));
</script>
... more page content
... another "display: none" div and accompanying script
... rest of the page content
<script type="text/javascript">head.js( { 'application': 'application.js' }, { 'landing': 'landing.js' } );</script>
</body>
</html>
First ask yourself this question: Do i really need all this javascript loaded when a user visits my page?
When first loading your website, you actually only need the autocomplete-functionality, the rest isn't needed on load. So you could go for a seperated approach. My advice would be the following:
Build this page without any javascript-functionality and then enhance it with javascript, get rid of the inline styles and scripts.
After you have done this, load the scripts you actually need, you can do this in the head or just before the end of the body
Use a CDN for Jquery, jquery-ui, underscore and the other libraries. If a user already loaded these libraries from another website, you have a performance bonus.
Last of all, already asynchronously load the javascript needed later on, so the user already has the scripts when he hits the compare-button.
Small tweaks:
Use a tool like ySlow or the networking graph in your favorite browser to look for any bottlenecks. It looks like gzipping is not enabled, try and do that.
Do you really need to load the facebook/google/twitter/third-party stuff in the head or could that be done when the page is loaded?
Is the server as fast as possible? It looks like it takes almost halve a second to get the HTML.
I hope i helped you out for a bit, good luck with the performance tweaking!
You could put mask layer that cover all pages with fixed style, then hide or destroy it when loading process finished. That way there's no need to hidden each content, instead it will be covered with mask div
I think, put a load scripts on the bottom of the page (as the last tags in the body). That javascript it will not block the drawing page, like now.
Saw the view source of your page.
There are some inline scripts which can block rendering. Such as this
Application.i18n = {"comparisons":{"off_ratio":
More here. http://calendar.perfplanet.com/2012/deciphering-the-critical-rendering-path/
Quick way: Moving them to the end of body tag.
Best way: They should be loaded as external scripts - with very good cache headers.
May be, you are doing that as - you have to load those messages based on user locale - You can create separate JS files for every locale during your build process - an they can be linked / loaded as external JS files with good cache headers
Another reason, why you might need inline scripts - to take note of the initial loading time. which is not necessary - as the modern browsers provide us with perfomance timings.
http://www.html5rocks.com/en/tutorials/webperformance/basics/
Moving it as an external script file - will also be good for your site security - in case, if you will be trying CSP.
http://updates.html5rocks.com/2012/11/Content-Security-Policy-1-0-is-officially-awesome.
Defer / async attributes.
ga.js is set with async attibute - but other JS files can be tried with defer attributes. Also, as a general rule of thumb, delay loading resources as far as possible,load only when it is needed.
window.onload - $.ready
Starting your script execution with $.ready is always going to be better than window.onload.
because, window.onload fires only after all the images, inner iframes gets loaded.
The following links might be useful.
https://developers.google.com/speed/
The Progressive JPEGs post in http://calendar.perfplanet.com/2012/
http://blog.chriszacharias.com/page-weight-matters
http://www.igvita.com/2013/01/15/faster-websites-crash-course-on-web-performance/
A lot of further optimisations are possible. All the best.

Where is the best place to put JavaScript/Ajax in a document?

Apologies for the dumb sounding question, but I need the experts to clarify.
Out of the three places to put JavaScript, head, $(document).ready, or body, where would the best place be to put some ajax that uses a lot of $GET functions?
For instance I am using a JavaScript function called execute_send() but I am unsure where the best place to put it would be. Below is the error:
Problem at line 67 character 22: 'execute_send' was used before it was defined.
function execute_send() {
Also how does the placement affect the page loading time?
In general, unless for some reason you need it elsewhere, put all of your JS last in the body. The browser won't continue until it's parsed your JS, so it is nice to let the page load first. See http://developer.yahoo.com/performance/rules.html
As an example of when you might actually want to put JS in the head: You might have some A/B testing code that you want to run before the page even renders - in that case, the code should go in the head, because you really do want it to run as soon as possible.
As #Thom Blake said, in general the best place is at the bottom of the <body> (+1 for that) - but I'll expand on that a bit:
The reason for this is that as the browser loads the page, it has to stop loading and parse the JavaScript when it encounters it. So if you have all your scripts in the <head> for instance, there will be a delay in loading all the content in the <body>
Note that this is a delay in loading - separate from the actual execution of the script. Something like $(document).ready() deals with when the script is executed, not with when it is loaded.
Generally, all this matters because you want a web page to feel as responsive as possible, so a best practice list for JavaScript will usually be along these lines:
Place all your scripts at the bottom of the <body> so that the loading of non-JS resources, such as images, is not delayed.
Combine your scripts into a single file, so that the server has to make fewer requests for resources (you'll see this referred to as "minimizing HTTP requests")
Minify you scripts, to reduce their total size, which speeds up loading times
Put any code reliant on the DOM (eg click handlers, HTML manipulation, etc) inside $(document).ready() (or the equivalent method for the JS library in use on the page).
Same subject : whats-pros-and-cons-putting-javascript-in-head-and-putting-just-before-the-body
In the past, i experienced some jquery problems has it was not 'loader' when initialising .. this is why we decided to insert it in the <head>.
In some situations it's not easy to move scripts to the bottom. If, for example, the script uses document.write to insert part of the page's content, it can't be moved lower in the page. There might also be scoping issues. In many cases, there are ways to workaround these situations.
For the rest of javascripts, all before the closing </body> tag.
To explain the 'Why page will load faster' : It wont.
Browsers are single threaded, so it’s understandable that while a script is executing the browser is unable to start other downloads. But there’s no reason that while the script is downloading the browser can’t start downloading other resources. And that’s exactly what newer browsers, including Internet Explorer 8, Safari 4, and Chrome 2, have done.
The difference is visible has your ressources within the <body> tag will load/show sequencialy. When the browser gets to load <script src=...js> the complete file has to be loader before the browser can fetch another ressource. So, it's an illusion, because the browser will load/di more 'visible' content before 'javascripts'.
To visualise the whole thing : firebug > Net (tab)
As stated before, $(document).ready is not a place. (For jQuery, $(document).ready simply ensures that the DOM is fully loaded (ready to manipulate) before any script is executed.) You would place your JavaScript in the <head> or the <body>.
However, putting all of your JavaScript includes and JavaScripts at the bottom of the <body> section is best for loading performance. "Progressive Rendering" and "Parallel Downloading" are blocked for everything below the scripts. If your scripts are the last thing on the page, you're not blocking anything.
This article explains it in more depth.
Example:
<html>
<head>
<!-- MY HEAD CONTENT - LOAD ALL CSS -->
</head>
<body>
<!-- MY HTML CODE -->
<!-- START javascript -->
<script type="text/javascript" src="/ajax/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="/ajax/jquery/plugins/jquery.random_plugin.js"></script>
<script type="text/javascript" src="/includes/some_other_scripts.js"></script>
<script type="text/javascript" language="JavaScript">
//<![CDATA[
$(document).ready(function(){
// my jQuery/JavaScript code
});
//]]>
</script><!-- END javascript -->
</body>
</html>

Loading a script in the <body> section

I have a javascript for a specific page that I do not wish to be loaded in my header section. Is it possible to load it in the section of the HTML.
Currently I have all my js code inside the but I want to remove it to a seperate js file that I can load.
I tried using this but it did not work.
<script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.5.1.min.js"></script>
Thanks
Q1 : I have a javascript for a specific page that I do not wish to be loaded in my header section. Is it possible to load it in the section of the HTML.
-Yes you can load javascript any where you want, if writing inline code then make sure you add script tag around your code.
-also you can request files like in body
Q2: Currently I have all my js code inside the but I want to remove it to a seperate js file that I can load.
-- no problem in that, thats even better practice.
Q3 Requesting external file
to request external files you write below written fashion
<script src="http://file_name.js" type="text/javascript"></script>
It's not only possible (ref), it's frequently a good idea.
Putting your scripts as late in the page as possible, which frequently means just before the closing </body> tag, means the browser can parse and display your content before stopping to go download your JavaScript file(s) (if external) and fire up the JavaScript interpreter to run the script (inline or external).
Putting scripts "at the bottom" is a fairly standard recommendation for speeding up the apparent load time of your page.
Yes it is possible. Try and see.
For debugging, hardcode the jquery full path.
It is sometime recommended to load it at the end of the of the body, to make the main content of the page load faster.
Is it possible to load it in the section of the HTML.
Yes.
From the spec:
<!ELEMENT BODY O O (%block;|SCRIPT)+ +(INS|DEL) -- document body -->
SCRIPT is among the elements that may be a child of the BODY elements. Numerous other elements may also have SCRIPT children.
<script type="text/javascript" src="<?php echo base_url();?>js/jquery-1.5.1.min.js"></script>
When I run echo base_url() I get my the hostname of my server. This would result in a URL such as example.comjs/query-1.5.1.min.js. You probably should drop that PHP snippet entirely and just use: src="/js/jquery-1.5.1.min.js" which would resolve to http://example.com/s/query-1.5.1.min.js.
Yahoo engineers recommendation for higher performance is to include your scripts at the end of your HTML, just before </body> tag. Therefore, it's even better.
To see where the problem is, you gotta first make sure that your js file is loading. User Firebug and go to scripts tab. Do you see your script? If not, then something is wrong with your path.
it should work...
Did you try to view the generated source and see if the PHP code indeed generated the right path?
beside that, it is recommended to load jQuery from a CDN such as google's :
https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js

Categories