Import stylesheets and javascript on the fly - javascript

I have a website whose navigation is all done via ajax (with jquery); each page is dynamically loaded into an element on the page. While I have a universal stylesheet and JS scripts, each page also has a page-specfic stylesheet and JS script. What is the most effect/efficient way to load these page-specfic scripts and stylesheets? On page load, most of the page-specfic scripts/stylesheets will not be needed. A page's scripts/stylesheet will only be needed when a user loads in (via ajax) a particular page. Should I load every single script and stylesheet at page load?
Another option would be to simply append appropriate <link> and <script> elements to the head when a page is dynamically loaded; however, would they be called? Also, would I need to remove the <link> and <script> elements when a different page is called (via ajax)? For the scripts, I could use jQuery's .getScript() function. What is the best approach to this in terms of efficiency and cross-browser support?
Thank you!

Js and CSS are one time load and are browser cached (depends on your server conf as well)
So if you have an ajax, with just 1 JS inclusion. You could
Insert this JS at the footer of your home page (lazy loading; pre-emptive thinking .. faster 2nd pages)
Bring the include JS tag along with ajax response. (nothing complex here. browser makes fresh JS call)
Combine all your JS/CSS into one combined JS, push it to home page head tag (eyeing performance and caching)
once document ready, do similar to #1 using getScript() as you suggested

Well one way I know of that this can be done is with RequireJS,
but the downside is that all the JS you have need to be defined as AMDs.
Don't know if you know anything about RequireJS, but its quite a neat library,
you can imagine it as a dependency injector and loads files in async way.
If you are interested you can check their docs:
Intro
CSS

Before I have commented what you could do with the CSS.
This is how you can work with js:
var script = document.createElement('script');
script.src = "path to your src";
// load event
script.onload = function () {
//some staff
};
document.head.appendChild(script);
Also, for you, I'll recommend reading this gist.
Another good information.

Related

Is it possible to include a specific javascript file on click?

I am currently working on a website that includes several very large Javascript files. These files are causing the load time of the page to become very slow.
The output of the javascript files are initially hidden to the user behind several jquery tabs. I was wondering if it is possible to load the files only when the user clicks on those specific tabs so that the initial load time of the website wouldn't be slow?
Javascript files can be loaded dynamically upon demand when you need them.
This will be an asynchronous operation so you will start the loading process and then some time later the script will be loaded and available to you.
In jQuery, you can use $.getScript().
Example:
$.getScript("test.js", function() {
// script is loaded now
// code that uses this script can go here
});
FYI, there are other techniques for improving the load time of your site. For example, you can put all non-essential scripts (those not involved in the initial display of your page) at the very end of the <body>, right before the </body> tag. This will allow your page to display without waiting for those scripts to load.
Scripts can also be marked async and defer so that other aspects of page loading will NOT wait for them to load.
Other useful references on this topic:
Script Tag - async & defer
Deferred scripts and DOM
load and execute order of scripts
improving website performance by dynamically loading javascript?
Yes you can do this. See
http://community.sitepoint.com/t/dynamically-loading-js-script/40207/15
You will probably have to do some string concatenation in the filename when writing out the src attribute so its loads the different file you require

Issue of javascript loading

First question:
About Dynamic Script Elements
var script = document.createElement ("script");
script.type = "text/javascript";
script.src = "script.js"; document.getElementsByTagName_r("head")[0].appendChild(script);
The important thing about this technique is that the file is downloaded and executed without blocking other page processes, regardless of where the download is initiated. You can even place this code in the <head> of a document without affecting the rest of the page.
I want to know what is difference between Dynamic Script Elements and this codes
<script type="text/javascript" src="script.js"></script>
Why does Dynamic Script Elements download and execute file without blocking other page processes and the other will?
Second question:
I know that the page download and rendering must stop and wait for the script to complete before proceeding, so I put scripts at the bottom before </body>
Is it necessary to use XMLHttpRequest Script Injection or other libraries like lazyload when I put scripts at the bottom, and why?
Anybody know this? Thanks
I want to know what is difference between Dynamic Script Elements and
this codes
Your code snippet is a dynamic script element. It is added dynamically to the page and is not natively present in the HTML of the page.
Script tags present in the HTML of the page are executed sequentially as the browser encounters them during the parsing of the page. The first script element is executed before any others, then the second and so on. Because there can be script elements embedded anywhere in the HTML of the page and they must execute in sequential order, a script element in the page must load and be executed before the rest of the HTML after it can be parsed and added to the page.
Why does Dynamic Script Elements download and execute file without
blocking other page processes and the other will?
I'm not sure what kind of answer you're looking for here. It works this way because this is how the designers of the browser/HTML specs decided it would work. A dynamically added script executes asynchronously, independent of the loading of the page. A script element present in the HTML of the page executes in a predictable order with respect to both other scripts and with respect to the loading of the page elements. This can be very important for some types of scripts (such as document.write() and thus the designers of these specs allow you to have either predictable, sequential order (which by its very nature must block until complete) or asynchronous loading. The defer and async attributes also allow you to change the behavior of even script tags that are present in the HTML of the page. So, this way you can have whichever behavior is most advantageous.
Is it necessary to use XMLHttpRequest Script Injection or other
libraries like lazyload when I put scripts at the bottom, and why?
No, it is not necessary to use script injection. Putting a script at the bottom of the page will allow the page elements above it to show to the user without waiting for the script to execute (if that is your goal). There are many other reasons for dynamically loading scripts besides just page load performance. For example, some scripts are loaded only when needed based on what action the page is going to execute.
For a lot more info about the execution order of scripts including the effect of the defer and async attributes in script tags, see this detailed post: load and execute order of scripts
The position of the script tags has something historical. In the early easy was often document.write() used to the Dom could change that is why a script block can block the rendering. However there is a attribute which says I don't change the Dom go on.
Script tags at the end of the page are related to the time when the download process is triggered so this can optimize the load process.
That lazyload libs are helpful of you need some other frameworks/libs only under some runtime conditions. It's all about page load times and how fast the page react on user interactions.

How can I load js files in specific pages using jQueryMobile?

It's a known fact that jQueryMobile loads pages with ajax and is not including in DOM the header content in every pages.
I need to load a custom js file in some pages, how can I achieve this? Until now I have placed the .js files in the body, but there are some problems with the code there too so it's not a good workaround. Until I can find a solution I will use the rel="external" workaround, but I really need to find an answer to my question.
You could try including the custom script within the data-role="page" div in pages where you want to use those javascript.
From JQM docs:
Another approach for page-specific scripting would be to include
scripts at the end of the body element. If you include your custom
scripting this way, be aware that these scripts will execute when that
page is loaded via Ajax or regular HTTP, so if these scripts are the
same on every page, you'll likely run into problems. If you're
including scripts this way, we'd recommend enclosing your page content
in a data-role="page" element, and placing scripts that are referenced
on every page outside of that element. Scripts that are unique to that
page can be placed in that element, to ensure that they execute when
the page is fetched via Ajax.
You could use some javascript to dynamically add the js file to the DOM.
This is demoed here: http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml

JavaScript in <head> or just before </body>?

I am about to embark on a new web project and I plan to put some JavaScripts in the <head> and also some before </body>, using the following scheme:
Scripts that are essential for the UX of the page: in the <head>. As I've picked up perusing the web - scripts in the <head> is loaded before the page loads, so it would make sense to put scripts that are essential to the user experience there.
Scripts that are non-essential to the design and UX (Google Analytics scripts etc.): before the </body>.
Is this a sensible approach?
Another approach would be to put all the scripts in the <head> and add defer attributes to the non-essential scripts. However, I read that older versions of Firefox don't pick up the defer attribute.
I think a lot of developers run JavaScript just before the </body> so that it is run after all the elements have been rendered.
However, if you organise your code correctly, the position on the page doesn't matter.
For example, when using jQuery, you can ensure the code isn't run until the page and its elements are fully rendered by doing the following:
$(document).ready(function(){
//Code here
});
Then the script reference can be put in the head tag.
Script tags should be referenced just before </body>. This prevents render blocking while the scripts load and is much better for site perception speed.
No obtrusive JavaScript should be used when using this technique.
JavaScript code should be placed at the end of the document so that it doesn't delay the parallel loading of page elements. This does then require that the JavaScript code is written in a specific way, but it does improve the speed of page loads.
Also, ideally you could host references like this under a different (sub)domain. References to jQuery should be pointed to Google's CDN too.
See Best Practices for Speeding Up Your Web Site for more information.
One of the reasons you'd want to put scripts before the </body> is if they manipulate the DOM without user interaction, so you'll need the DOM to be loaded in order to be manipulated. Another way to do that is to add an event listener and run the scripts when the page has loaded, but this will require additional code, which might get complicated if you have a lot of scripts, especially ones you haven't written yourself. Putting them at the end of the page also will speed up page load, though in the case of DOM manipulating scripts you might get some not-so-pretty results from that.
I'd say that's perfectly sensible. As you said, as long as you don't move essential scripts (e.g. jQuery, Modernizr, etc., etc.) out from the <head>, you shouldn't have problems.
Moving non-essential scripts to the bottom of the page should help with the perceived loading speed (that and minimizing / concatenating scripts).
It all depends on what you mean by "essential for UX". I agree with having Modernizr appear early for example, but not everything needs to load straight away. If you're trying to avoid a flash of unstyled text (FOUT), that's a good reason. Similarly, if you have scripts that affect how the page looks before the user does anything, you should load those early.
Don't forget though, speed is part of UX. There's no advantage in having some jQuery interaction ready to run when the user can't see the content it applies to yet. The difference between loading the scripts at the start of the end is a matter of seconds. If you let the page load first, the user will be using those seconds to take the page in, allowing you to load scripts unobtrusively.
Your page will load faster if you move scripts to the bottom of the page, and that makes a difference to your pagerank these days.
Also, some versions of Internet Explorer will throw errors if you try to run a script before the element it refers to has loaded.
Like Ed says, your scripts should be stored in a separate file, and in as few files as possible.
Put the JavaScript code in a separate file and place a link to it in the head part of the HTML.

How to prevent external JS to block your site from loading?

how do I prevent slow loading external js files from blocking the loading process of the whole website (because the browser processes 2 requests only at a time)?
Let's say I want to include the sharethis button but the server is encountering heavy load and needs to long to serve my request, how can I force the rest to load anyway. Or should I add the external scripts after the site has loaded already?
I'm using RoR with jQuery.
Best,
Ole
Personally I would load the extra items after the ones that you need.
For example add the code to bottom of the page so that jQuery has already loaded and then load them from jQuery like below
$(document).ready(function(){
$.getScript("urlofscript");
});
Details of getScript() here
You should dinamycally load the external JavaScripts by using $(document).ready() function of jQuery.
You'll have to create the <script> elements and append them to your document.
place your javascripts the end of the page, just before < /body>
Definitely place this blocking script at the end of your page, before </body>.
Or if you want to lazily load it / don't actually need the script for the page to load, then the document.write() option is good.
I also recommend reading the web page optimization rules from this page: http://code.google.com/speed/page-speed/docs/rtt.html.
Or read either of Steve Souder's books: "High Performance Websites" and "Even Faster Websites"
Just put the <script> elements at the end of the document (just before the </body> tag).

Categories

Resources