I have a jquery-code which using selectors (from current document). Now I want to move this code into another file(js) and just include from this document. Could I do it without any editing? So, will jquery-code works right?
<script src="jquery.js"></script>
<script src="main.js"></script>
in the head or right before the end body tag will do. If this is in the head then make sure you're using $(document).ready( fn ).
Yes, all the selectors you currently use are relative to the DOM of the web page/document that you are working on. Whether the javascript code that produces and uses these selectors is embedded in the html page or included from an external js file is not relevant. (Though this latter layour is much preferable approach for other reasons)
To quote and expand on meder's answer
<script type="text/javascript" src="/SCRIPT_DIR/jquery.js"></script>
<script type="text/javascript" src="/SCRIPTS_DIR/main.js"></script>
Would be a better way to declare the javascript. Note the script type is specified and the src URL starts with a / character which specifies an absolute reference to the script file, which is good practice for nested pages.
Related
I'm trying the following but it doesn't appear to be working:
<script src="/script.js">
alert(hello);
</script>
Script.js simply contains var hello = "world".
Can you not put code between <script src="...">CODE RIGHT HERE</script>?
If I skip src it works:
<script src="/script.js"> </script>
<script>
alert(hello);
</script>
You can specify the src attribute or include the code as the content of the script tag. As you've discovered, you can not do both simultaneously.
Here's what Mozilla Developer Network has to say about the src attribute (emphasis at the end added):
This attribute specifies the URI of an external script; this can be used as an alternative to embedding a script directly within a document. script elements with an src attribute specified should not have a script embedded within its tags.
You can also come to the same conclusion by carefully reading the W3C Recommendation at http://www.w3.org/TR/html5/scripting-1.html but I don't see it stated so concisely. (Correction welcome! Maybe I'm just not seeing it.) You have to follow along the steps to preparing a script.
Technically it can be done but only if the script you're referencing with the src attribute evaluates the contents using something like:
eval(document.currentScript.textContent);
However I would advise against doing this as it violates standards.
I include the jquery external js file with the command:
<script type='text/javascript' src='js/jquery-1.11.0.js' ></script>
I will call it again in the same page a little bit below (this is because I am including this with php classes to make sure it is loaded before going on). So in the page, I will have 2 times the line at different places:
<script type='text/javascript' src='js/jquery-1.11.0.js' ></script>
I want to know if this will create problems in my page and if the script jquery will be loaded 2 times which would be inneficient.
Thanks,
John.
This will create issues for any plugin that is included between those two inclusion.. For example if you have :
<script type='text/javascript' src='js/jquery-1.11.0.js' ></script>
<script type='text/javascript' src='js/jquery-plugin.js' ></script>
<script type='text/javascript' src='js/jquery-1.11.0.js' ></script>
jquery-plugin.js will be overwritten and it will not work.
It will be included twice. There is no need to do it. If you absolutely must write the include tag in two places do it second time conditionally. Code below will include jQuery only if it is not included yet.
<script>
window.jQuery || document.write('<script src="js/jquery-1.11.0.js"><\/script>')
</script>
It should be fine, especially in modern browsers, but it is a little bit strange to do this.
If at any point you load jQuery plugins after the first script tag, these will no longer work because jQuery/$ has been re-initialised.
I can't think of any reason you would need to load this twice, though - are you sure you need to? Your best bet is to put the script tag at the bottom of the page, before closing the <body> tag.
Depending on the library, including it more than once could have undesired effects.
Think of it like this, if you have a script that binds a click event to a button, and you include that script twice, those actions will be ran twice when the button is clicked.
You could write a simple function that you call to load a script and have it keep track of files that have already been loaded. Or, I'm sure you could probably use a pre-existing JS loader such as LabJS and modify it.
Reference: What is the danger in including the same JavaScript library twice
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
I have a every common page a.html which looks like this:
<html>
<head>
<script type="text/javascript" src="xyz.js" > </script>
</head>
<body>
<div> ... </div>
</body>
</html>
In b.html, I use jquery's .load() function to a div.
$("#myDiv").load("a.html")
It works. The xyz.js's content is loaded along with a.html. But why isn't there a <script> tag? I open firebug to see the source. There is a's but no a's <script>.
I want the <script> because I need it to find relative path.
(this question)
Edit: I tried to use .get() and .html(). Didn't help.
Edit2: The title is not very appropriate. The xyz.js runs. But no <script>.
The .load() function purposefully strips out <script> tags from the loaded content. When you give it a plain URL to load, it will execute the scripts after loading the content and adding it to the DOM. However, if you use the trick of adding a selector after the URL in the first argument:
$('#foo').load("http://some.domain.com/blah #special-div");
then it strips the <script> tags but it does not execute them.
Why? I don't know.
Now, please note that loading an entire page from the <html> tag on down into an element of another page is going to result in some sort of Frankenstein monster of a DOM, if a browser will do it at all. Generally, when you use ".load()" to grab fragments of content to update a page, your server should respond with a piece of a page, not the whole thing. The jQuery deal with allowing a selector after the actual URL is intended to let you strip out a chunk of a page, which is really cool, but it has that drawback that the scripts won't be executed in that case.
Because, it cannot run the script inside the <SCRIPT> tag. jQuery has .getScript() to call for scripts only. Check here
The context: My question relates to improving web-page loading performance, and in particular the effect that javascript has on page-loading (resources/elements below the script are blocked from downloading/rendering).
This problem is usually avoided/mitigated by placing the scripts at the bottom (eg, just before the tag).
The code i am looking at is for web analytics. Placing it at the bottom reduces its accuracy; and because this script has no effect on the page's content, ie, it's not re-writing any part of the page--i want to move it inside the head. Just how to do that without ruining page-loading performance is the crux.
From my research, i've found six techniques (w/ support among all or most of the major browsers) for downloading scripts so that they don't block down-page content from loading/rendering:
(i) XHR + eval();
(ii) XHR + inject;
(iii) download the HTML-wrapped script as in iFrame;
(iv) setting the script tag's async flag to TRUE (HTML 5 only);
(v) setting the script tag's defer attribute; and
(vi) 'Script DOM Element'.
It's the last of these i don't understand. The javascript to implement the pattern (vi) is:
(function() {
var q1 = document.createElement('script');
q1.src = 'http://www.my_site.com/q1.js'
document.documentElement.firstChild.appendChild(q1)
})();
Seems simple enough: and anonymous function is created then executed in the same block. Inside this anonymous function:
a script element is created
its src element is set to it's location, then
the script element is added to the DOM
But while each line is clear, it's still not clear to me how exactly this pattern allows script loading without blocking down-page elements/resources from rendering/loading?
One note first:
(iv) setting the script tag's 'async' flag to 'TRUE' (HTML 5 only);
async is a "boolean attribute", in the HTML sense. That means that either of the following is correct:
<script async src="..."></script>
<script async="" src="..."></script>
<script async="async" src="..."></script>
And that both of the following make the script be loaded asynchronously, but are not conforming (because of the possible confusion):
<script async="true" src="..."></script>
<script async="false" src="..."></script>
Now on your question. The point is that it is the HTML parser that is being blocked by the script (because people do stupid things things like document.write("<!--"), even from external JS files, and expect it to "work"). However, in your case (vi), the HTML parser doesn't ever see the script element, because it is added to the DOM directly. Somewhat logically, if a script element (or rather, a <script> start tag) isn't seen by the HTML parser, it can't stop the parsing either.
I will try to say everything with one URL, it will save us both time.
Please have a look at this presentation from the author of a book that addresses topics such as the ones you are mentioning. I found the presentation (there is a youtube one also - i think in the google channel) very very interesting. It explains much of what you want to know.
http://www.slideshare.net/souders/sxsw-even-faster-web-sites
http://www.youtube.com/watch?v=aJGC0JSlpPE (long video many details on performance params/topics)
Your last example modifies the DOM tree and can only be used after the DOM tree is complete (onload). So the browser is already able to fully render the page, while you're loading the js script.
Here is a example how firefox renders 2 different versions:
img http://img177.imageshack.us/img177/9302/40229406.jpg
test.html loads with your method above within onload at the bottom of the page.
test2.html loads with an simple script tag in head.
Note the red line, this is when the onload element is triggered.