jquery load time and css styling inside it - javascript

like you see in the code below, the jquery loads a page but it seems that all the .css styling inside the jquery waits until the jquery is loaded which can take some fraction of a second if the file is big. So if I have .css("display","none") it will not work for that time causing a flickering before the styling kicks in. I have this problem only with Mozilla. The code below its only an example and it works well because is small. Some ideas how to fix this?
$(document).ready(function() {
$(".rectangle").click(function() {
$("body").load("debugging2.html", function() {
$(".rectangle").css("display","none")
$(".rectangle").fadeIn(1000);
}) ;
});
})
.rectangle{
height: 200px;
width: 200px;
background-color:#000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
<div>
<div class="rectangle"></div>
</div>
</body>

$(document).ready(function() {
$(".rectangle").click(function() {
$("head").append("<style>.rectangle{display:none;}</style>");
$("body").load("debugging2.html", function() {
$("rectangle").fadeIn(1000);
});
});
})

Since script tags are loaded synchronously (by default) they indeed block page rendering. It can result in blank unstyled page if HTML is not processed and styles are not loaded by that moment. Hence the common very simple solution is to move heavy script tags to the very end of the </body> and put necessary CSS style in the <head>.
As the result of above, CSS gets downloaded first, after HTML is loaded quickly, rendered and styled and only after that slow scripts get downloaded.
In code it will look something like this:
<head>
<link href="style.css" rel="text/css" type="stylesheet">
</head>
<body>
<div>
<div class="rectangle"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- some other scripts -->
</body>
As the bonus, you don't need to bind to document ready event anymore ($(document).ready(function() {});), since HTML is all loaded by default, when scripts are executed.

Related

How do I apply loaded javascript and css to .load() content?

I am loading .html content with jquery .load() but the javascript and css is not applied to the one.html/two.html after it is loaded by the .load() function.
Example below:
<head>
<style> styles1 </style>
<link href="stylesheets/style2.css" rel="stylesheet">
<script src="script1.js">
<script>
$(document).ready(function(){
$("button.os").click(function(){
fillmein = $(this).attr("target");
fillmeinfile = $(this).attr("target")+'.html';
$("."+fillmein).load("/contentfolder/"+fillmeinfile);
});
});
...
other scripts
...
</script>
</head>
<body>
<p>the css and any js is applied to this block</p>
<button class="os" target="one">replace</button>
<div class="one">I will be replaced by one.html</div>
<button class="os" target="two">replace</button>
<div class="two">I will be replaced by two.html</div>
</body>
I understand that the one.html/two.html is loaded after the styles and javascript is loaded by the browser but how I get the styles and javascript that is in the <head> to apply to the newly loaded one.html/two.html?
I new to jQuery so let me know how I clarify if needed. thanks!
EDITED
Thanks for providing answers everyone! Updated the code example to clarify what I meant.
copying the <style> and <script> into the one.html and two.html works but if I load the javascript twice it could conflict. for example, having logic that searches $(document), and functions that collapse and expand a section can be called multiple times. Is it possible to have the js and css that was loaded in the main page work on the newly loaded .html files or is there any clean and DRY way to do this?
As suggested by Arun P Johny in his comment
You simply put your CSS inline on the target document and it will be automatically loaded along with the content.
You can write
$('button').on('click','Classname',function(){
//write your structure here
})
This will work for all tags with 'Classname',which are already present or dyanamically added later on.

Add a class name to element immediately this element is loaded

I have an element which has to be hidden when JavaScript is enabled. The current code seems like this:
<body>
...
<div id="js-hidden"></div>
...
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$('#js-hidden').hide();
})
</script>
There is the problem, the js-hidden div is visible since the rest of page (and JavaScripts) are loaded.
Can I hide that earlier? This solution is so bad for me, JS user can´t see this element.
PS: I've written the example with using jQuery, it can be in plain JS too, of course :-)
$(document).ready makes it happen after full page loaded you can use
<body>
...
<div id="js-hidden"></div>
...
<script src="jquery.js"></script>
<div id="js-hidden"></div>
<script>
$('#js-hidden').hide();
</script>
Simplest thing:
<style>
.js-hidden {
display: none;
}
</style>
<noscript>
<style>
.js-hidden {
display: block;
}
</style>
</noscript>
Since you cannot use onload event on div I guess the best solution is put your js right after that div...

JQuery Messed Up Page on Load

Not quite sure how to define this issue. I just started working with jQuery and Javascript and pretty much everything is fine, except for when the page initially loads. I have the page fade in, but it looks like all the CSS isn't being applied until the jQuery loads.
I tried this script in my Head tag, but it doesn't work. Help?
<script type="text/javascript">
$(function(){
$('#box-container').hide();
});
$(window).load(function() {
$("#box-container").show();
});
</script>
Whoops: site: http://www.elijahish.com
You should use a Javascript console like Chrome Console or Firefox Firebug to debug your code.
First, you are placing your script block which requires jQuery before jQuery is defined:
<head>
<script type="text/javascript">
$(function(){
$('#box-container').hide();
});
$(window).load(function() {
$("#box-container").show();
});
</script>
...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
...
So you would see the following (in Chrome Console):
ReferenceError: $ is not defined
$(function(){
Second, you seem to be trying to run a script which is accessing (in the first block) an element (#box-container) before it has been seen in the DOM itself. You could use jQuery.ready on that first block, but that could be messy. I would instead suggest you place this right after <div id="box-container"> is defined:
<body ...>
<div id="box-container" ...>
...
</div>
<script type="text/javascript">
(function($){
$('#box-container').hide();
$(window).load(function() {
$("#box-container").show();
});
})(jQuery);
</script>
Demo: http://jsfiddle.net/5JpVB/4 (I use a setTimeout for dramatic effect.)
Or put it directly after the <div ...> is opened:
<div id="box-container">
<script type="text/javascript">
(function($){
$('#box-container').hide();
$(window).load(function() {
setTimeout(function(){
$("#box-container").show();
}, 2000);
});
})(jQuery);
</script>
Box Container shown on window.onload.
</div>
http://jsfiddle.net/5JpVB/5/
And the coup de grâce (document.write nothwithstanding):
<head>
...
<script>
document.write('<style>#box-container{display: none;}</style>');
</script>
...
</head>
http://jsfiddle.net/5JpVB/2/
Yes, that is a script that "puts" the style display: none into the header, which "neatly" bypasses some of the conjecture that's been thrown around (there's downsides for each method, more or less). There's an elegance to this method (except, of course, using document.write, which is icky).
And yet another way, using the CSS display: none method:
<head>
...
<style>
#box-container {
display: none;
}
</style>
...
<div id="box-container">
<noscript><style>#box-container{display: block;}</style></noscript>
Box Container shown on window.onload.
</div>
http://jsfiddle.net/5JpVB/3/ (Just the Result page, disable Javascript to see it work.)
You are getting a case of FOUC : http://www.bluerobot.com/web/css/fouc.asp/
And, years later we are still plauged! http://paulirish.com/2009/avoiding-the-fouc-v3/
A variety of solutions are included on this link.
You could also set the style of your content to be hidden before running the javascript that shows the content. Jared shows you a nice way to do this.
Might I make a suggestion that you use combination of CSS and JavaScript, rather than one or the other. I had the same issue using jQueryUI on a site I'm building and found that a lot of these solutions out there would make the contact unavailable to those without JavaScript.
So here is what I did:
CSS:
.flash #wrapper {
display: none;
}
What this does is set the <div id="wrapper"> to hidden only if it is a decendent of the class flash. So to keep it from being hidden from those with out javascript I add the class flash to the <html> element. So it can only be physically hidden if the end user has JavaScript enabled, otherwise they'll at least have access via the unstylized content.
JavaScript:
$('html').addClass('flash');
$(doctument).ready(function() {
/* Do all your stuff */
/* When done show the wrapper with the content stylized */
$(#wrapper).show();
});
Depending on your pages time to load you might get a little flash, but it wont be a flash of unstylized content, which is rather ugly. In my case I had a jQueryUI menu item that would flash the normal <ul> element first then the menuUI item, and my <div> elements are resized with jQuery so that each <div> column is equal hight, but it would flash the different heights first. This fixed it while still giving accessability to none Script enabled browsers.

Keeping javascript external - doesn't work

When i keep my javascript/jquery external, my code doesn't work. but when i combine them in my html file everything is fine.
any suggestions as to why this is?
here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type ="text/javascript" src="jquery.js"></script>
<script type ="text/javascript" src="program.js"></script>
</head>
<body>
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
</body>
</html>
with external javascript
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
VERSUS
<!DOCTYPE html>
<html>
<head>
<script type ="text/javascript" src="jquery.js"></script>
</head>
<body>
<div id="clickme">
Click here
</div>
<img id="book" src="book.png" alt="" width="100" height="123" />
<p>First Paragraph</p>
<p>Second Paragraph</p>
<p>Yet one more Paragraph</p>
<script>
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
</script>
</body>
</html>
I guess you execute the click event before the DOM finishes loading. Wrap your code inside the dom ready event and it should work, Assuming your path to the external javascript file is correct.
$(function(){
$('#clickme').click(function() {
$('#book').fadeOut('slow', function() {
// Animation complete.
});
});
$("p").click(function () {
$(this).slideUp();
});
});
Always use firebug (console) to see what is wrong with the script, if you run into any script errors.
Your javascript is executed before there are elements on the page. You can get around this by using $(document).ready(function(){...}); or moving your external javascript files to the bottom.
Wrap your js code in external file in
$(document).ready(function(){
//your code goes here
});
Right now you are including external js file in header and it is executed. At this point there is no elements so $('#clickme') and $("p") are empty set. In the second example you run this code after rendering html with that elements.
The reason that there is a difference, is that in the external file your code is executing before the browser has fully parsed the DOM so you are attempting to programatically access elements of the page which the browser is not yet aware of. This is exactly what most people have already said, but let me elaborate a bit further...
Whilst a lot of people have mentioned using jQuery's document ready handler, I would like to point out that a workable solution is simply to move your script tags to the bottom of the page.
Not only will this solve your problem in itself, but it will also improve page load times because of how browsers treat scripts. When the browser encounters a script it stops everything else it is doing (known as a "blocking" operation), and parses and executes the script. This causes the page to just appear to stall from a user's perspective, meaning a bad user experience. Thus, because the scripts are parsed and executed only as they are encountered, by moving your scripts to the bottom you allow the browser to fully render the page so that the JavaScript does not block rendering.
Though rather than just moving scripts to the bottom of the page, I'd also follow what the others recommended and wrap the whole code in the document ready handler just to be extra safe that your code will always be executed at the correct time.
Also, in the debate of inline or external, external scripts are generally preferred as they are easier to maintain and the browser can cache them independently of the page (providing the correct HTTP headers are present).
To sum up here's some example code:
<html>
<head></head>
<body>
<!-- all your markup here -->
<!-- script at bottom, markup already rendered by this point -->
<script type="text/javascript" src="jquery.js"></script>
<!-- inline or external, still wrap in document ready handler -->
<!-- though external is better because the browser can cache it independently of the page -->
<script type="text/javascript">
//wrap in document ready to be extra safe
$(function() { /*code here*/ });
</script>
</html>

Removing page load 'glitch' while jQuery executes

Users in my site are seeing a half-second glitch on each page before any jQuery code executes. This code manipulates the page so you can visibly see elements move in one big chunk, making the user experience feel clunky. I'd prefer the page not to display at all until the JavaScript has run.
I'm using jQuery provided by the Google API in a page as follows:
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3.2");
</script>
<script type="text/javascript" src="MyScript.js"></script>
In MyScript.js:
google.setOnLoadCallback(runOnLoad);
function runOnLoad() {
// Do stuff
}
Does anyone know if it's possible to run the JavaScript before the page is displayed in the browser?
You could probably add a css class to your main div that would hide the content, and then remove that class as the last thing that MyScript.js does.
In your html template:
<body>
<div id="mainContent" class="hidden">
</div>
</body>
The css class:
.hidden
{
display: none;
}
Last executed statement of MyScript.js:
$("#mainContent").removeClass("hidden");
I would agree with Jan.
Most (not all) browsers load CSS first before javascripts.
So CSS would be advisable for you.

Categories