I have a webpage with mostly basic HTML on it. There is one section where I load an RSS feed using JavaScript pulling from an external source (url). The problem is that my page will load everything up until that script, wait for the script to load (sometimes up to a few seconds), then load the rest of the page.
How can I force it to load the script after it has rendered the entire page first?
My code is something like this:
<html>
<more html>
<script language="JavaScript" src="http://..." type="text/javascript"></script>
<more html>
...
Two options:
Put your script block at the end of the page. This is good practice anyways due to the fact that your page strucutre will load before the script that is intended to manipulate it. Because the user generally notices the page loading but not the script, this gives the appearance of a faster load overall.
Include the defer attribute in the opening script tag. Note that defer can only be used on external script files (those with an src attribute). See https://developer.mozilla.org/en-US/docs/HTML/Element/script.
Add the defer attribute to the script tag in the head also works
<script language="JavaScript" src="http://..." type="text/javascript" defer></script>
Reference link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#attr-defer
A pretty reliable way to make a script load after pageload is to write out the script include itself in javascript.
var theScript = document.createElement("script");
theScript.setAttribute("type","text/javascript");
theScript.setAttribute("src","//www.mysite.com/script.js");
document.getElementsByTagName("head")[0].appendChild(theScript);
You could try wrapping the function that calls the feed in
jQuery(window).load(function(){
//embed RSS feed
});
forcing it to load last.
Move your script tag to the end and it will load after everything else. For example:
<html>
<more html>
<more html>
<script language="JavaScript" src="http://..." type="text/javascript"></script>
</html
Related
Hi guys I’m new to JavaScript and web development. I came across this question recently about the location of the script tag. I know it’s a common question and I’ve viewed some answers on stackoverflow also this style guide on google. but I am still not very clear on this problems.
For example, I have I html page with an external script js file like this
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script src='js.js'>
</script>
</head>
<body>
</body>
</html>
and the js file is
var loadTime = document.createElement('div');
loadTime.textContent = 'You loaded this page on: ' + new Date();
loadTime.style.color = 'blue';
document.body.appendChild(loadTime);
It seems to me that this js file is not dependent upon any DOM elements of the html file being available so it should not matter where I put this script tag. But it turns out I have to put this script tag to the bottom of the body closing tag, otherwise the date won't appear on the page as expected. Another workaround is using defer attribute in the script tag like this
<script src='js.js' defer></script>
This is what baffles me, if a script has any operation related to DOM, it seems to me that it cannot be put at inside the head tag at the front without a defer or async attribute in it. Why this google style guide https://developers.google.com/speed/docs/insights/BlockingJS still suggest we can write inline script in the head tag given accessing and operating on DOM are incredibly common in any script file.
According to http://caniuse.com/#feat=script-defer, 94.59% of all browsers support this. 94.92% support it at least partially. Why the async and defer attributes are not used widely? I mean, I viewed a lot of HTML sources out there, and I just don't see the async and defer attributes anywhere?
So here are some explenations.
Using <script></script> in HTML without any extra attributes will block HTML parsing (in other words 'loading html to browser window') from that point. Specified script will be then fetched and executed upon successful download. After that, execution will be resumed (page will be loaded).
Using <script async></script> allow HTML parser not to block parsing until the script is downloaded.
Using <script defer></script> allow HTML to be fully parsed, and script code will be executed after that.
So to anwser your question from the topic - scripts in <head></head> can be included (and will work properly) if they do not require to acces things that are not there yet.
In your example you are trying to append sth to body (which is not yet there).
If you are using <script async></script> in <head></head> it is also not guaranteed to work. Eg. script is tiny (almost instant download) - it will be executed before html is fully parsed (results in accessing things that are not there yet). We can time async requests, it's part of their beauty.
Using async makes sense if fetched script is not accesing DOM straightforward.
Using defer makes sense eg. if JS file is big (eg. fetch takes 5sec) and we want to show user sth. on the page. After script is loaded we change the page to it's inteded 'look' via js in script.
Note that these are not all use cases of async and defer.
Suggest you check the answer of this load and execute order of scripts
The normal way is in the head tag only loading the javascript.
Then after the whole html file is loaded, in the document onload call your functions.
document.addEventListener('DOMContentLoaded', function() {
console.log('document - loaded - ');
//call your functions
}, true);
Curious at to where I place my Jquery and Bootstrap files. They recommend that you always place at the bottom for performance purposes yet when I check sites that use Jquery/Bootstrap the majority of users always place them at the top. Also should I be loading my own JavaScript files before or after the bootstrap/Jquery files?
I take it that I load the my own css file first before the bootstrap file if I want to override some of their styling, is this correct and does the same apply to javascript files?
Typically stylesheets in the head and scripts before the closing </body> tag:
<html>
<head>
<link rel="stylesheet" href="bootstrap.css">
<link rel="stylesheet" href="your-other-styles.css">
</head>
<body>
<!-- content -->
<script src="jquery.js"></script>
<script src="bootstrap.js"></script>
<script src="your-other-scripts.js"></script>
</body>
</html>
You'll want files from vendors such as jQuery and Bootstrap to be included before yours. This means that:
CSS: You can override their styles with your own*
Scripts: You have access to any objects added to the global scope such as window (jQuery adds $,
for example)
However, if you require a script to be available before your content loads (such as Modernizr), then putting it in the <head> ensures it's ready before any of your content.
Including scripts at the bottom ensures that the actual page content is loaded first; when the scripts are finally downloaded the content (DOM) will be ready for your scripts to manipulate.
* assuming your selector specificity is at least equal to those in your vendor CSS
Bottom is best to place all your script references at the end of the page before </body>.It should look like below in normal page.
<html>
<head>
<link href="path/to/file.css" rel="stylesheet" type="text/css">
</head>
<body>
<script src="path/to/file.js" type="text/javascript"></script>
</body>
</html>
Although in some cases it may be necessary to load JavaScript before page load if any of your function need to access JavaScript before Page Load.Specially if you are working with JQuery UI And Bootstrap.
You can decorate your script tags with the defer attribute so that the browser knows to download your scripts after the HTML has been downloaded:
<script src="Jquery.js" type="text/javascript" defer="defer"></script>
or
<script src="demo_async.js" async></script>
When present, it specifies that the script will be executed asynchronously as soon as it is available.
http://www.w3schools.com/tags/att_script_async.asp
If you need script to access in page for use then script need to available before using it. Although it need to be sure the browser support defer="defer". Async is supported by all major browsers.
Javascript by default block any other parallel downloads. So if you have many tags in the head, calling on multiple external scripts will block the HTML from loading, thus greeting the user with a blank white screen, because no other content on your page will load until the java script files have completely loaded. Another advantage to load script in bottom is that any error caused by external script will not stop the page from Loading to browser.
Style css need to present in top <Head> to access in page.
It really depends on what you want to achieve, but generally JS is placed at the bottom and CSS in your head section. Make sure that jquery library loads before Bootstrap's JS library and your custom css file loads after Bootstrap's CSS, so it will override. You can load Bootstrap's CSS from their CDN (or others, like cloudflare - for example http://cdnjs.com/libraries).
Make sure you minify all that & activate compression and you shouldn't experience any performance issues.
Advanced techniques imply using the most important part of your CSS in your head area, then send the rest of the CSS in the bottom area. Or have your whole static content (CSS + JS) hosted on a CDN.
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 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
Does the page load faster if i use the javascript before the </body> tag? Example:
<body>
balbllb content
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
$(function(){
});
</script>
</body>
The page will still load in the same amount of time, but it might be perceived as loading faster (i.e. you might see DOM element(s) appearing quicker).
If it was me, I would leave your jQuery.js reference in the <head>, and keep your custom stuff before the end of <body>.
I don't know whether it loads faster (I would be surprised) but in this case you no longer need to wrap your code in a $(document).ready as at that moment the document will be ready to be manipulated:
<body>
balbllb content
<script type="text/javascript" src="jQuery.js"></script>
<script type="text/javascript">
// directly manipulate the DOM here
</script>
</body>
Its not about anything happening faster. Its the order in which things happen. Putting scripts at the bottom (right before the closing body tag) makes it so the rest of your content loads before loading the scripts, making it appear that its loading faster.
The total page load time will be the same. But the page will be perceived as loading faster since it will appear to the user faster. The "perception of loading faster" is not a conjecture, it is a fact, proven many times by psychologists.
Remember that if you load your JS libraries at the bottom of the page (as you should), then any dependent scripts must follow the libraries at the bottom.