Hi I'm experiencing some problems including a javascript file in my html project.
When I include it like this at the end right before the body tag my site does not work correctly.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</body>
If, however i delete the tag at the end to make it look like this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"/>
</body>
everything works fine.
And if i include it within the head, it also works, independent of the syntax.
Why does it behave like this?
Do what everybody else has said, regarding the <script src="..."></script>
Use just src="//...", instead of src="https://..." or on non-encrypted pages (http vs https) your visitors will get security warnings for mixing the two protocols
If you have written jQuery code anywhere on the page, prior to actually including the file, you're going to get reference errors, where JS will not be able to find the function ($) you're trying to use.
There is a debugger available if you use Chrome, and press CTRL+SHIFT+J : it will take you to the developer-console, where I'm sure you're going to see all kinds of reference errors.
In Firefox, it would be CTRL+SHIFT+K, in IE it's F12.
This works under the same premise as writing in other languages where you try to use libraries or other classes, but don't actually import them until the bottom of your program.
For browser compatibility, you must use the first form:
<script src="https://..."></script>
with an explicit closing tag </script>. If this is the case where your code is not working, then your real problem lies elsewhere and not in the way you close the tag.
There might be some race condition happening for you... it will be good if you can provide complete code... if you attach that in header ... then your jquery is successfully loades and then executes your body part... if your attaching that in body ... then closure of script is give some issues... try to play while changing your script code placements in you body tag.
</script> closing is compulsory to work in cross browsers
This might help you in ur debugging.
Why do you want to load jquery in the end of your code? If you have some other scripts that need jquery, then they should be loaded after it. So either you put all script tags in head or in the end of body — jquery should be loaded before other files that depend on it.
Related
I have a script on my site from easypolls.net which is basically a voting poll but if for example their site is down, or there is a problem loading the script then the rest of the content on my site isn't loading.
Here's the script:
<script type="text/javascript" src="http://www.easypolls.net/ext/scripts/emPoll.js?p=5075b1e0e4b08bb807c01061"></script><a class="OPP-powered-by" href="http://www.objectplanet.com/opinio/" style="text-decoration:none;"><div style="font: 9px arial; color: gray;"></div></a>
So how can I fix this, is it normal javascript issue? or am I doing something wrong?
The script is inside a div in the body section.
If you are currently referencing this script in the HEAD of your document, then you might try adding that script tag right before the closing BODY tag.
I would use js library such as yepnope.js to make an asynchronous call to that js file with errorTimeout property set 2-4 sec? and if it cant be retrieved you can always notify user in corresponding callback functions. Display message, hide the poll? or what ever you want with js/jQuery or similar.
There is some good information about this issue by Steve Souders
Are you trying to load your site in IE? Because IE breaks sometimes when a script file doesn't load properly.
Also try this:
<script type="text/javascript" src="http://www.easypolls.net/ext/scripts/emPoll.js?p=5075b1e0e4b08bb807c01061"></script>
Add a closing bracket to the end of the script. This is good practice, and might solve some problems
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>
I have no idea how to describe this accurately/intelligently because it seems to be completely impossible, yet there must some reason for it.
I am trying to leverage jquery, jquery-ui, qtip (tooltip for jquery) and highcharts (javascript charting), but for purpose of post I could just as easily been only using jQuery and jQuery-UI.
If I include my <script/> tags at the bottom of my <head/> element I get an error trying to call the .slider() extension to configure my sliders. But if I put the <script/> tags right before the closing of my <body/> element then everything works. To illustrate, the following will not work (obviously some pseudo code below):
<head>
<script jquery.js/>
<script jquery-ui.js/>
</head>
<body>
... html ...
<script type="text/javascript">
$(document).ready(function () {
$(".slider").slider( { .. options .. } );
} )
</script>
... more html *including* the .slider elements
</body>
However, if I move the two jQuery script tags to be right above the </body> closing element things work. When the script tags are in the head element and I debug my application, basically the page does appear to have completely loaded and Visual Studio highlights the line calling the .slider() function saying it doesn't know what slider() is. Looking at the call stack, it appears to be correctly calling it from the document ready function...the mark up all appears to be there as well, making me believe the document truly is ready.
Now I didn't include things that are required by asp.net 1.1/2.0 site in my pseudo code, namely a <form/> element with runat="server' and the use of a <asp:ScriptManager/> tag (we needed that for parsing monetary values from different cultures leveraging Microsoft Ajax). I can't believe they would be causing the problem, but maybe they are. Additionally, asp.net injects several of its own script sections (i.e. for validation, post back, etc.)
Regarding the form tag...all the html and document.ready markup would be inside the form tag, while the script tags are always outside of the form tag (either above it, in the head or below it at the bottom of the body).
Obviously I could leave the script tags at the bottom, and I very well may end up doing that, but I am trying to get a clean 'template site' of which to use when creating new client sites and it just feels wrong that I have a restriction forcing me to put those tags at the bottom of the html. I'm sure our framework code (or maybe asp.net's) is simply inserting something that is causing problems/conflicts with jQuery, but I don't really know how to go about debugging/diagnosing what that problem is. So if anyone has any suggestions I'd greatly appreciate it.
It looks like jQuery 1.3.2 is being loaded by ASP.NET (see your second WebResource.axd). The two library versions are overwriting each other. Thus the reason it works when you load 1.6.2 at the end of the page.
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.
I have searched this web looking for an answer, but it seems that this time I'm not so lucky, so I am forced to ask. I apologize if it's already answered (could not find it). And yes, English is not my first language, so I also apologize for my spelling mistakes, I try my best.
This is my problem, using Tomcat 5.5, Struts 1.3, JRE 1.5 and I'm using firefox 3.5.6.
In my jsp page I cannot seem to put any src="path/path" in my <script> I have tried deleting the src and all works well, but my project is going to need a lot of use from jquery and I do not want to copy/paste all the js file in every jsp.
This is my code:
<script type="text/javascript" src="js/jquery-1.3.2.js">
function showMySelf(){
alert("Hello World!");
}
(... plus other stuff code that actually uses jquery functions)
</script>
and the submit button:
<input type="submit" onclick="showMySelf()">
When I click the button, nothing happens (well it actually repaints the page) and when I delete the "src" tag from the script and add all the jquery code to the page it all works well.
I have tried putting another slash in the path as "/js/jquery-1.3.2.js" and returns an error.
I have tried using ResolveURL and it doesn't seem to give me better results.
I have also tried changing the js file to another file ("generics.js" and "js.js"), I also tried with "js/*.js".
Any of theese solutions have archived anything.
I have also tried using the struts tags (like html:submit) but it also did not work.
The path is actually right, since looking the code in my web browser gives me a link to the js file. So I suposse the browser knows were to look for my js file, it does not give me an error or a broken link to the file.
Any ideas of why this is happening?
Thank you all.
Random.
You can not use a script element to load an external file and put code in it at the same time. You need to use two script elements:
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">
function showMySelf(){
alert("Hello World!");
}
(... plus other stuff code that actually uses jquery functions)
</script>
I think Gumbo solved it.
As a sidenote, a very good way to find out whether a browser can load a JS file is the "Net tab" in Firebug in Firefox. It shows all loaded (and failed) requests of the current page.
The two most likely options are:
a) You are including HTML in your JS file (i.e. <script> tags)
Take it out.
b) You have the wrong URI and when you attempt to resolve your relative URI manually you do so incorrectly
Look at your server access logs to see what is actually being requested (or use a tool such as Firebug)
The first thing to do in such case. Install Firebug and look at the "Console" panel (for possible syntax errors) and the "Net" panel to see whether your jQuery sources are being fetched correctly. The 2nd column there shows the request status code.
alt text http://img46.imageshack.us/img46/6224/jqueryfirebugtmp.jpg
(full size image)