I've been doing some testing with http://www.webpagetest.org/ today to see which scripts are slowing down my page loads. Long story short, I've discovered that third-party scripts are causing a noticeable slowdown in loading. I'm loading them all at the bottom of the page, using async and defer ( see https://www.igvita.com/2014/05/20/script-injected-async-scripts-considered-harmful/ ).
I believe the main reason for the slowdown is not just in grabbing the files from the third-party, but in actually running the various scripts, especially side-by-side with mine.
I'd like to keep all the scripts, but I want them to be loaded behind the scenes, after all my scripts have loaded, and with no noticeable performance decrease in the browser. For example I don't want the browser to "stutter" or jump around if I start scrolling down while the third-party scripts are loading, or various other minor annoyances.
Has anyone tackled this before and come up with a good solution? So far I'm thinking the best option might be to load the third-party scripts using jQuery.getScript(), after all my scripts have finished (literally at the bottom of one of the .js includes). Still, that may load them all concurrently which could make the browser sluggish for a second or two.
Some more details on how I did the testing, for anyone interested:
grabbed the source code of a product page, threw it into a test PHP page so I could modify it at will
surrounded each script with an on/off flag such as
if ( isset( $_REQUEST["allowGoogleAnalytics"] ) ) {
ran a test with all scripts turned off
in new tabs, ran more tests, turning scripts on one at a time
by the time my own scripts were all turned on, the pages were taking about 1.9 seconds to load (first view) and less than a second on repeat view. This is fine with me.
after turning on the third-party scripts, the pages were taking at least 3.1 seconds to load (first load) sometimes as much as 3.9
The third party scripts in question are:
facebook "like" button
google +1 button
pinterest
google trusted stores
None of these are particularly bad on their own, but all at once they combine and take too long, and make the browser too sluggish.
You can queue scripts, if problem is in simultaneous load. Also this load should be started on document ready (i see you already using jQuery, so use it in example).
Example code (tested locally, works).
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
var scripts2load = [
"http://apis.google.com/js/plusone.js",
"http://connect.facebook.net/en_US/all.js#xfbml=1"
];
function loadNext() {
var url = scripts2load.pop();
if (url) {
$.ajax({
url: url,
cache: true,
crossDomain: true,
dataType: "script",
success: loadNext
});
}
}
$(loadNext)
</script>
In the past I have had some success waiting until the page was fully loaded (which happens after DOM Ready). Any scripts that you load before window.load causes the browser to do more work on top of the parsing/rendering/resource loading it's already doing. Traditionally, we do everything on DOM ready - which can quickly give the browser a lot to deal with. Instead, split off any of your non-crucial functionality and let the browser deal with them after all the crucial stuff has been dealt with.
Try taking your non-crucial scripts (eg. like buttons, anything not crucial to the page) and wait to load them until window.load. Then apply a fade-in effect or something else to ease-in the display. If window.load is too long to wait (ie. you have a bunch of images on your page), then you can do something like this:
$(function() {
var timer = setTimeout(loadThirdPartyScripts, 1200),
$window = $(window);
$window.on('load.third_party', loadThirdPartyScripts);
function loadThirdPartyScripts() {
clearTimeout(timer);
$window.off('load.third_party');
/* load your scripts here */
}
});
This will load all of your non-crucial scripts after the window has loaded or after 1.2 seconds - whichever comes first (adjust the timeout as needed). If you have a lot of images - I suggest lazy loading ones below the fold - the whole point being to get window.load to fire as soon as possible.
Disclaimer: if you wait until window.load to load a dozen or two resources, you are still going to experience the same stutters that you are now.
Related
On a clients webpage, the page uses js/css to style a tree-style view to the desired look of the client. But on some of the pages with many objects it takes some time for the styles to load. So I suggested adding a loading screen.
Here is an example of the issue: http://zamozuan.com/content/16-search-auto-parts-by-vehicle-chevrolet
My client purchased a little animated icon they like that fits the theme of their site nicely.
I have a very simple addition to the script to add a loading icon, and then on $(document).ready, hiding the load element and showing the main element.
All works fine except the loading gif is not animating until AFTER the page has completely loaded.
It seems that the loop for the js is too intensive so the gif is not animating.
Before anyone chops my head off, I did view the similar questions on here, but those solutions do not work for me - the majority of issues are in IE and my issue is in chrome (not IE), and most of the other options are work-arounds based on clicking buttons to enable/disable, but in my case this is when the page initially loads so that is not viable.
I am wondering, is there any work-around to fix this? Is it possible to pre-load the gif in to an animated status and somehow prevent JS from interfering? Or is there a way to make the js loop not be so intensive that it completely freezes the browser?
As for the code, it is the exact as the link above, with only this added at the end:
$('#loading').hide();
$('.mainsearch').first().css('display', 'block');
The loading element just contains:
<img src="img/loading.gif" class="img-responsive">
<p class="centertext">Loading, please wait...</p>
But as mentioned, the gif does not load, just freezes.
For the javascript that is styling the tree, you can view it here:
http://zamozuan.com/js/tree.js
Any help would be greatly appreciated, as my client would not want to waste this loading icon they bought.
Thanks.
No, there is no work-around. It's not a problem with how the image is loaded, it simply won't be animated while the script is running.
Javascript is single threaded. As long as a script is running, there is no visual updates in the browser. This includes GIF animations, while the script is running animations won't move.
Without being able to work on the actual code and try it, I would suggest trying to break up your looping into separate callbacks. Maybe using setTimeout or requestAnimationFrame for every few recursions to give the browser a chance to update/paint.
<script type="text/javascript"
src="http://s7.addthis.com/js/250/addthis_widget.js"></script>
I am using this code for facebook, twitter etc, but there is a script in this which makes the page loading speed extremely slow. Can you please help with the solution for this, the entire code is below
<!-- AddThis Button BEGIN -->
<div class="addthis_toolbox addthis_default_style ">
<a class="addthis_button_preferred_1"></a>
<a class="addthis_button_preferred_2"></a>
<a class="addthis_button_preferred_3"></a>
<a class="addthis_button_preferred_4"></a>
<a class="addthis_button_compact"></a>
<a class="addthis_counter addthis_bubble_style"></a>
</div>
<script type="text/javascript">
var addthis_config = {
"data_track_addressbar": true
};
</script>
<script type="text/javascript"
src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-4dfeea6f5bf22ac6">
</script>
<!-- AddThis Button END -->
Besides moving everything to the bottom of the page as Mudshark already said, you can also use the async addthis version:
http://support.addthis.com/customer/portal/articles/381221-optimizing-addthis-performance#.USyDXiVuPYo
<script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#async=1"></script>
function initAddThis(){
addthis.init()
}
// After the DOM has loaded...
initAddThis();
One of the solutions would be to use deferred JavaScript loading pattern for AddThis library.
There are several nice JavaScript libraries helping you out with that problem. I personally use mostly Modernizr.load (or yepnope.js by itself)
You can read more on that issue and improvement in Improve Your Page Performance With Lazy Loading article.
As a side note, I was able to improve page load by about 35% average in my past projects by using deferred JavaScript loading patter. I hope that will help.
One obvious thing to do would be to move the javascript to the bottom of your page, right before </body> so that everything else can load before it.
put async="async" attribute to your script tag
<script type="text/javascript"
src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-4dfeea6f5bf22ac6" async="async">
</script>
There are few things to note:
you really don't need to load addthis immediately, you can load it relatively late during page rendering process,
addthis .js file is huge, currently around 118kb, minimized and gzipped (sic!),
due to its size it will always take relatively a lot of time for browser to compile and process it, especially on mobile devices.
Using async attribute in the script tag might help, however browsers consider mostly network resources when they see the attribute. Browsers don't take into account what impact the script might have on CPU usage, page rendering tree etc. (in browsers defence there's no way for them to determine it). For example scripts that take a long time to execute might block rendering of first frame or other crucial early paints. Even if we ignore network resources (connection slot, bandwidth etc.) required to fetch the addthis .js file it still may turn out that the script has severe impact on page loading process.
Note that while the async attribute hints browser that the resource can be loaded asynchronously it says nothing about the script execution when it is finally retrieved. JS in browsers is mostly single threaded and once browser start to process the .js file it can't back out of it and it has to let it finish running.
On my computer, evaluating the script in Chrome takes ~130-140ms and it blocks ParseHTML event for that long. On less powerful mobile devices it may easily jump to 500ms.
Because addthis is so big it would be best give browsers a little help and defer .js file fetch until other, more important components of page are displayed. You should use dedicated .js deferring library for this task to make sure that it is processed after DOMContentLoaded event and after other important resources are processed. I personally use Lab.js for this as it's small and does its job well.
Note also that there exists defer attribute that you can add to script tag, however specification clearly states that the script with defer tag present has to be processed before DOMContentLoaded event - so no wins here.
I have a page (A) which is a heavy javascript page, when I leave this page to go to page B it takes a long time. When I go to page B from a different page it is really fast. So it has something to do with page A and probably its javascript.
When I run the network profiler from the developer tools in IE 9 it shows a gap of ~15 seconds between the response and the DomContentLoaded(event).
Page A is heavy with javascript because it runs the Xopus Editor, a rich text XML editor.
Does anybody have any ideas on what I could do to either analyse the gap as to what happens or what I could do to make Page A unload faster.
This is a long shot as there are about eleventy-hundred things wrong with it, but it might be somewhere to start. Add this script tag to your page as the very last one:
<script>
function unloadJS() {
var scripts = document.getElementsByTagName("SCRIPT");
for (var index = 0; index < scripts.length - 1; index++)
{
var file = scripts[index].getAttribute("src");
var start = +new Date();
scripts[index].parentNode.replaceChild(document.createElement('script'),
scripts[index]);
var elapsed = +new Date() - start;
alert(file + ": " + elapsed.toString());
}
return false;
}
</script>
This code attempts to force the unload of each of the JavaScript files that were loaded on the page, reporting the amount of time it takes to drop them in milliseconds. Fire this as is convenient, i.e., on unload or with a button:
<button onclick="return unloadJS()">Go!</button>
This might not work/tell you what you need to know because IE could refuse to do garbage collection when the script is disconnected. This could be because IE really doesn't unload them when you do this, or just because IE - well, what oddi said :)
In any event, this isn't a solution; it doesn't matter when the JS gets unloaded, garbage collection still takes the same amount of time. This is just an attempt at a first diagnosis, like you asked for. Hope it works/helps...
Yes IE sucks. But there are several tools to profile your page.
Fiddler or HttpWatch is a good tool for analysing your request timeline and see whether it takes long time to download all your heavy javascript code. It's often the main cause of slowing down a heavey js page. Since IE doesn't take parallel downloading js very well, it costs more time for hundreds of small javascript files.
For this case, try minifying your javascript. It is the most direct way to enhance your page load performance.
If it doesn't help much. You may need YSlow to analyse a detailed performance. Although it doesn't fits IE, fixing some issues under Chrome or FF can affect performance under IE.
Add some log in your console, narrow down the scope maybe you can find the execution performance problem.
Maybe you're using a Javascript library like PrototypeJS that hooks onto the page unload event and when the page unloads, it loops through an array removing all the event listeners for all the DOM elements on the page. If we know what libraries you are using, we could simulate a call to unload the page to force the library to execute it's unload function. Afterwards, start a timer to see how long it takes to load another page.
I have implemented the Facebook like button on my site by using the asynchronous JS SDK and it's working great! However it takes a long time to load, which is not a great problem (Would be nicer if it loader quicker though..) as the rest of the page loads fine.
However, if your view the the site in any version of IE the whole page is unresponsive until Facebook Like / comments have loaded... All the images and other scripts are loaded, but the whole page is locked.
Any ideas on how i can rectify this for IE users?
I have seen this post: How do I keep the Facebook like button from delaying the loading on my website? but this was solved by using the Async version, where as mine IS using this and still hanging?
If it helps I can post a link to my site / page that it appears on?
Well, my only advice here is to place your FB JS code just before the </body> tag. But I have other "tips" for your site in general.
Try to minify/combine your CSS and JS files when possible
Try moving your JS code to the body tag (at the end)
Do you really need the Prototype AND jQuery libraries?! try removing one of them and port the functionality to the other (almost all tasks can be done with either library)
In the end, IE was hanging because I had a CSS3 transform on my images and apparently this slows down IE (Even though it cannot render the transform. So i can disable by this via conditional comments in the CSS or in my case modernizr.
I am working on optimizing a page that has Flash on it. I am using optimization practices like moving Javascript to the bottom to not block. Removing inline scripts. And minimizing HTTP requests with minified css and js.
The majority of the pages content is in the flash, so loading it as soon as possible is the goal. Currently there is a 2 ~ 3 second delay before the flash is even rendered (using firebug profiling)
I am wondering at what point in the page load does the browser start initializing flash on the page?
Is it once the DOM element containing the flash has been rendered?
Is it once the complete onload event has been fired?
I imagine it probably differs with each browsers as well.
Use a direct embed in the HTML. Don't use swfObject or the JS that the Flash IDE provides. If you use JS, you have to wait for that file to load - and then chances are, the JS is attaching to the window.onload and not rendering the SWF until then.
First, none of the major browsers wait for flash before displaying the page. This means that when the HTML page finishes loading, the Flash content may not be completely loaded yet.
I assume based on these facts that the SWF loads simultaneously with the HTML. Once the HTML is loaded then the SWF is displayed.
To test you could use https://addons.mozilla.org/en-US/firefox/addon/3371/
To improve flash loading try SWF Object:
http://code.google.com/p/swfobject/
Because Flash is treated the same way as CSS and HTML by all browsers, a browser initializes it when loading HTML (they're both loaded at the same time). The browser does not prioritise Flash above anything else.