YUI: ensuring DOM elements and scripts are ready - javascript

If I put my inline script after the DOM elements it interacts with, should I still use YUI 3's domready event?
I haven't noticed any problems, and it seems like I can count on the browser loading the page sequentially. (I already use YUI().use('node', ... to make sure the YUI functions I need have been loaded since the YUI script is a separate file.)
Is there a way to speed up the loading of widgets like YUI 2's calendar?
I load the appropriate script in <head> element of my page. I use YUI().use('yui2-calendar', ... to make sure the Calendar widget is available. Unfortunately, this causes a short but noticeable delay when I load my page with the calendar. If I omit the YUI().use('yui2-calendar', ... code then it shows up without a noticeable delay - but I guess this could cause the Calendar to not show up at all if the YUI script doesn't load in time?
With regards to #2, is it possible to reduce the visual artifact of the calendar not being present and then showing up?
I've made it slightly better by specifying a height and width for the parent div so that at least the space is already allocated => minimal shifting around when it does load.

You don't need domready if the code that accesses DOM elements comes after those elements in the markup. This applies to DOM scripting in general, not just YUI.
yui2-calendar is not identical to yahooapis.com/2.8.0r4/build/calendar/calendar-min.js. The former includes some wrapping code to sandbox the Calendar API and its dependencies in the YUI 3 instance environment. If you're including the YUI 2 scripts in the <head> (which you arguably should place at the end of the <body>), you don't need to use yui2-calendar. Doing so just loads the Calendar code twice. Otherwise, to leverage YUI 3's dynamic async loading, you can remove the <script>s from the <head> and just use('yui2-calendar'). You can get the appearance of speeding up the time to render by including the yui2-* combo <script> in your markup after the yui-min.js seed file. Note the Loader will always fetch the css file, so you don't need to include that in the markup.
<script src="http://yui.yahooapis.com/combo?3.1.0/build/yui/yui.js"></script>
<script src="http://yui.yahooapis.com/combo?2in3.1/2.8.0/build/yui2-yahoo/yui2-yahoo.js&2in3.1/2.8.0/build/yui2-dom/yui2-dom.js&2in3.1/2.8.0/build/yui2-event/yui2-event.js&2in3.1/2.8.0/build/yui2-calendar/yui2-calendar.js"></script>
You can include the css and markup of a rendered Calendar on page load, then render into the markup container. I don't think YUI 2 calendar has the notion of progressive enhancement of existing markup baked in, but I could be wrong. It should clobber the static table markup with its generated markup and vivify the UI.

If it's after the said nodes in question, then you don't need DOMContentLoaded (or domready).

Related

Render Scripts-Section after scripts were loaded in ASP.NET Core PartialView

In an ASP.NET Core app, I've a dashboard with widgets. Every widget has its own PartialViews, so the full page is generated in the following way:
-Layout.cshtml
--Dashboard.cshtml
--- Widget1.cshtml
--- Widget2.cshtml
Following best practices according to fast page load times, JavaScript is loaded before the closing </body> tag in Layout.cshtml. After that, there is a section for custom JS, which I commonly use to initiate objects on page load. So this section looks like this:
<script asp-append-version="true" type="text/javascript" src="~/clientscript/page.min.js"></script>
#RenderSection("Js", required: false)
In my Views, which are using the Layout.cshtml as layout (in this example, its Dashboard.cshtml), I can define a section like
#section Js {
// Js Code here
}
which is rendered after the script tag containing all script files. So I can be sure, that all dependencies like jQuery or custom classes are avaliable here.
But I also need to do this in widgets like Widget1.cshtml for example. The problem is: I load the PartialView Widget1.cshtml in Dashboard.cshtml. In the documentation is written, that this is not possible:
If you declare a Razor section in a partial view, it will not be visible to its parent(s); it will be limited to the partial view.
But that's exactly what I need. Is there a way to work around this limitation? Shortly, the goal is to inject JavaScript from a PartialView to the LayoutView, with an regular View between them.
The only way I know is the usage of setInterval() with a low interval like 50ms, and check there if jQuery or some of my custom class is defined in a loop until they are. Its a JS solution yes. But it makes it possible to include the script-block directly in the PartialView without making usage of sections. It fits well when you depend on a single variable like jQuery.
But I need to wait for custom classes to get loaded. They're included after jQuery. So writing a generic function like waitForTypeLoaded(type, callback) is not possible. It would cause me to write always the raw setInterval() code, which seems not a smart solution for me.
Something I did to get my scripts to run after Jquery was done loading was in my Partial Views and View Components I used the "DOMContentLoaded" event to load all my jQuery js script after the page was done loading. That way I could defer the Load of jQuery and Still Have jQuery code on my pages.
<script>
window.addEventListener('DOMContentLoaded',
function() {
$('body')....
});
</script>
Your problem can be solved as mentioned in my answer to this post:
How to render scripts, generated in TagHelper process method, to the bottom of the page rather than next to the tag element?
To sum up, you can create a pair of tag helpers, one that can be located in a partial view and just stores its content in a temporary dictionary, and the other that renders the content at the appropriate position (e.g. in the layout page). I use it extensively to render small dynamically created scripts as the final scripts of the body.
Hope it helps.
Honestly, I would make one step back and look at architecture once again if you have such dilemmas.
Why not add to required scripts which will be used on a couple of views/partial views to the main layout? In ASP.NET MVC you can use bundling mechanism (or you can write our own) - minify and bundle them with other required. It won't be heavy...
Your approach looks like unnecessary complicated.

Eliminate render-blocking JavaScript and CSS - advice needed

Google PageSpeed Insights is flagging this as something I should fix - I've read the guidance on Optimising CSS Delivery at https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery but I'm confused at what the best practice is, and also on which resources are render blocking and which aren't?
Is Google suggesting removing stylesheet links from the page head and replacing with inline styles to make something render, then using Javascript to trigger an external stylesheet to load when window.onload fires? Won't this just delay process of arriving at the 'correctly rendered' page - isn't it better for the browser to start downloading the CSS as soon as possible?
Yes, that's pretty much what the page you reference is recommending. Put the minimal amount of CSS (as long as it's a small amount) directly in the HTML markup within a <style> tag. Then include the complete set of styles at the end of the document. (In the example, it's not actually loaded via JavaScript per se; rather, the link to the external style sheet is placed in a <noscript> tag. That's a bit of a hack, but it gets the job done. You could also request the stylesheet via AJAX and inject it using JavaScript directly.)
This approach only works if you can isolate the minimal CSS needed for your page and that amount of CSS is reasonably small. If, for example, you're building a single page web app, then many of your CSS rules might be for parts of the app other than the initial view. In that case, those extra rules can be put in the external style sheet. Or maybe you have a set of rules strictly for pop-up dialog boxes. Those rules can be postponed as well.
If you can't really separate your rules into those that are needed initially and those that aren't, and if your minimal rule set is large, you can't take advantage of this approach.

Should use Head.js or just minified scripts before </body> with scripts in the markup?

I have the optimisation problem — my site uses 2 (pretty large) javascript resources:
application.js (minimised jquery, jquery-ui, underscore-js and some shared scripts, 120KB total)
controller-specific file (some modules required for the page + interactions, 4KB total)
I have some scripts in the views that format/convert markup with JavaScript (dependable on both jQuery and my controller-specific JS code) so I need to wait either for $(document).ready or head.ready and it makes the part of website invisible to prevent the flash of unstyled content :(
Now my question comes: should I use head.js for it or just stick with the "before " scripts? Are there any smart ways to speed up page loading time in this case?
Update:
Here's the part of the code (see versusio.com for full code, landing page):
<html>
<head>
... usual stuff
<link (css stuff) />
<script src="head.js"></script>
<script>
// Here some global variables are set like cache keys, actual locale code etc., not dependable on jQuery or any other JS code from the JS assets
</script>
</head>
<body>
... page content
<div id="search">!-- here some code with the "display: none" style to prevent flash of unstyled content</div>
<script>
// Here is code that positions and processes some styles and adds some interactions to the #search div
Application.Position.In.Center($(#search), $(document));
</script>
... more page content
... another "display: none" div and accompanying script
... rest of the page content
<script type="text/javascript">head.js( { 'application': 'application.js' }, { 'landing': 'landing.js' } );</script>
</body>
</html>
First ask yourself this question: Do i really need all this javascript loaded when a user visits my page?
When first loading your website, you actually only need the autocomplete-functionality, the rest isn't needed on load. So you could go for a seperated approach. My advice would be the following:
Build this page without any javascript-functionality and then enhance it with javascript, get rid of the inline styles and scripts.
After you have done this, load the scripts you actually need, you can do this in the head or just before the end of the body
Use a CDN for Jquery, jquery-ui, underscore and the other libraries. If a user already loaded these libraries from another website, you have a performance bonus.
Last of all, already asynchronously load the javascript needed later on, so the user already has the scripts when he hits the compare-button.
Small tweaks:
Use a tool like ySlow or the networking graph in your favorite browser to look for any bottlenecks. It looks like gzipping is not enabled, try and do that.
Do you really need to load the facebook/google/twitter/third-party stuff in the head or could that be done when the page is loaded?
Is the server as fast as possible? It looks like it takes almost halve a second to get the HTML.
I hope i helped you out for a bit, good luck with the performance tweaking!
You could put mask layer that cover all pages with fixed style, then hide or destroy it when loading process finished. That way there's no need to hidden each content, instead it will be covered with mask div
I think, put a load scripts on the bottom of the page (as the last tags in the body). That javascript it will not block the drawing page, like now.
Saw the view source of your page.
There are some inline scripts which can block rendering. Such as this
Application.i18n = {"comparisons":{"off_ratio":
More here. http://calendar.perfplanet.com/2012/deciphering-the-critical-rendering-path/
Quick way: Moving them to the end of body tag.
Best way: They should be loaded as external scripts - with very good cache headers.
May be, you are doing that as - you have to load those messages based on user locale - You can create separate JS files for every locale during your build process - an they can be linked / loaded as external JS files with good cache headers
Another reason, why you might need inline scripts - to take note of the initial loading time. which is not necessary - as the modern browsers provide us with perfomance timings.
http://www.html5rocks.com/en/tutorials/webperformance/basics/
Moving it as an external script file - will also be good for your site security - in case, if you will be trying CSP.
http://updates.html5rocks.com/2012/11/Content-Security-Policy-1-0-is-officially-awesome.
Defer / async attributes.
ga.js is set with async attibute - but other JS files can be tried with defer attributes. Also, as a general rule of thumb, delay loading resources as far as possible,load only when it is needed.
window.onload - $.ready
Starting your script execution with $.ready is always going to be better than window.onload.
because, window.onload fires only after all the images, inner iframes gets loaded.
The following links might be useful.
https://developers.google.com/speed/
The Progressive JPEGs post in http://calendar.perfplanet.com/2012/
http://blog.chriszacharias.com/page-weight-matters
http://www.igvita.com/2013/01/15/faster-websites-crash-course-on-web-performance/
A lot of further optimisations are possible. All the best.

Is there a valid reason about putting JS in the head of document?

I mean : I know the JS is cached only if it come from a .js file. Also, 90% of my functions must be rendered when the page (html) is loaded (rendered), so it is better put JS before closing the body tag. (this prevent also to use document .ready(); and the loading of the page itself will be more faster).
So, which is the advantage on putting JS in the <head></head>? Expect the "order" of the code, which I don't mind so much to be honest...
Placing a <script src> tag inside the <head> section makes sense – semantically. It does block the browser from rendering anything until the script is loaded but assures that an object (e.g. jQuery) is available in the rest of your code (in the body for example).
A common practice is to load a light weight script loading library (HeadJs, LABjs, etc) inside the head section, then load the heavy stuff lazily and/or on-demand.
Having said that, HTML5 introduced the async attribute for script tags and re-introduced the defer attribute (docs). So you now have a very good and valid reason for putting <script src> tags inside head sections because:
it makes sense
the script still loads after the page has finished loading
The <script> tag causes two problems:
Everything below the script won't render until the script is loaded.
All components below the script don't start downloading until the script is done.
Putting it into the <head> only really makes sense if you need to execute some JavaScript before anything gets rendered.
So placing it as low as possible in the page would result in a better user experience.
It's slightly more semantic to put it in the header, but it doesn't generally have any advantages. Sometimes it is necessary - for example, loading fonts using JavaScript (using stuff like Google Webfonts) has to be done in the header, or the page will render with the wrong font and then change, which won't look good to the user.
The important thing about the elements in the <head> section are that they are loaded, before the <body> starts to load.
This is a very efficient feature, which are used a lot (IMO).
Loading of libraries, scripts, that have to run before the DOM has loaded have to done in <head> section.
I will give you a scenario
Imagine, You needed to calculate the 30% size of the screen's total size and assign it to the element inside.
It would be foolish and wait for the element to load big, then run the script to load resize it again.

Adding style and script tags to body acceptable?

I'm creating an AJAX heavy web application and I'm curious on what people's thoughts are on adding style and script tags to the body of an HTML document.
I've been using the jquery.load() method to insert content on the fly. An example partial HTML page that could get loaded into the body element is this:
<script type="text/javascript">
$(function() {
// All required java script for the control goes here...
});
</script>
<style type="text/css">
/* All required styles for the inserted HTML go here */
</style>
<div id="some-control">
<!-- Required HTML markup is here. -->
</div>
Since this HTML is getting loaded into a DIV, we are ending up with script and style tags that are not in the head but in the body of an HTML document. I'm not sure if this is valid HTML? Is this a common approach to developing AJAX enabled web applications? Are there any drawbacks I should be aware of?
As far as Javascript is concerend, you can put it any where on the page provided that elements it will work upon are loaded before and it does not throw the error undefined element. Famous Yahoo performance article and even Google (in terms of SEO) suggests to put javascript at the end of the page just before the </body> tag.
If you can manage to put your script just before </body> tag, that is considered good approach otherwise what you are doing now should be fine if everything is working properly for you.
I would actually disagree with Sarfraz and say that you should avoid using <script> and <style> tags in your page body as much as possible. The advantages of moving your JS to an external file are endless. The most obvious include:
leveraging on browser caching - if you just write code in your body, that's extra kilobytes of data that need to be loaded for every page. If it's a universal function, you're wasting precious load time. If it were in an external file, most modern browsers cache that file and only request a new version so often. This decreases server load as well (less requests)
Furthermore, if you ARE using a similar script on multiple pages, what happens if you need to make a change :(. Now you're running around searching for every instance of a <script> tag to make a change. Having all your code centrally located and universal allows for ONE change and DONE
Versioning - if you use version control (GIT, SVN, etc), it's much easier to track and revert one file (if you made a mistake or accidentally lost code) than all of them
CSS share a similar story. Again, with caching and centralized storage, and reusability. It's even more important, however, for styles to match on a website. From a UI standpoint, you don't want your fonts changing from page-to-page and you don't want to edit 40 pages every time you want to add a new style.
As far as having the JS in the document because you are using AJAX loaded content, I suggest you look into .bind and .live. They let you attach handlers to existing and future instances of a DOMObject. For example:
$('.class').live('click', function(){
alert('I was clicked!');
});
This will apply to any object that existed at page load AND objects that are later created. The following code will NOT - it only applies to objects created on load:
$('.class').click(function(){
alert('I was clicked!');
});
When I see that the big-site Content Management Systems routinely put some <style> elements (some, not all) close to the content that relies on those classes, I conclude that the horse is out of the barn.
Go look at page sources from cnn.com, nytimes.com, huffingtonpost.com, your nearest big-city newspaper, etc. All of them do this.
If there's a good reason to put an extra <style> section somewhere in the body -- for instance if you're include()ing diverse and independent page elements in real time and each has an embedded <style> of its own, and the organization will be cleaner, more modular, more understandable, and more maintainable -- I say just bite the bullet. Sure it would be better if we could have "local" style with restricted scope, like local variables, but you go to work with the HTML you have, not the HTML you might want or wish to have at a later time.
Of course there are potential drawbacks and good (if not always compelling) reasons to follow the orthodoxy, as others have elaborated. But to me it looks more and more like thoughtful use of <style> in <body> has already gone mainstream.

Categories