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

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

Related

jQuery/JS not removing JS functions on HTML wipe?

I have an issue with dynamically loaded content.
I'm using ajax calls to load in HTML content without refresh the browser, and pages have their own JavaScript libraries that need to load in order for them to work. So I embed that JavaScript content into the HTML which I load with ajax.
The problem is, that even though the HTML that had the embeded JavaScript gets removed, the functionality of those JavaScript functions is still loaded no matter if the HTML along with the JavaScript is removed.
That means, that if a certain page is loaded more than once, actions will fire the same amount of times that the pages has been loaded.
How do I make sure that JavaScript libraries get only loaded into the browser once, retaining the functionality of loading the source of the JS libraries with the ajax call, not just having source file links and then loading them again after the ajax call along with the required HTML is loaded? (load the JS files along with/before the HTML is loaded with ajax)
Once you load a JavaScript file into your browser's memory, it remains there until you load another page.
So... it doesn't matter how do you load it (through AJAX, or just once when page load through script link, or just embedding it into your raw HTML), once it's there it will remain there until you go to another page.
If you want your client code to execute only under certain circumstances you need to control that.
From my point of view your best option is to just load once your libraries and determine by code when execution should start, end, and repeat (if needed).

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.

pagespeed (chrome) not recognizing javascript defer

After I read pagespeed (chrome) suggestion to defer javascript, I modified the javascript link tag for three files, not all files.
However, when I load the website, pagespeed continues to suggest that I defer javascript, and the modified files continue to appear under the suggestion's list.
I have attached two images, one shows that pagespeed is suggesting I defer these javascript files, and the other is showing the pagesource, which lcearly shows that the javascript link tag includes the defer attribute.
PAGE SPEED IMAGE
WEB PAGE SOURCE CODE
For live website: http://redesign.com.s136249.gridserver.com/
Do you have any insight as to why this is happening (perhaps this files are not being deferred?) do you have any suggestions of what can I do to have pagespeed reflect the deferral of these javascript files?
Update:
Consider using the defer attribute!
Old Answer:
The concept is, that a script loading should be deferred, that is, it should appear after all of your contents.
Like just before the closing </body> tag, and that's the right way of saying it as deferred.
For now, what you have done, is just like ordering scripts.
And why is it asking you to defer it?
Whatever external files you specify in your code, needs an extra call to be loaded.
Until that call is resolved, the rest of the content of your page cannot be rendered by the browser, and have to wait, until your scripts are loaded.
Making this call in the initial part of the code, makes your site appear a bit slow.

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