How to asynchronously load CSS and JavaScript - javascript

Okay so how can I use loadCSS (https://github.com/filamentgroup/loadCSS/blob/master/README.md) to allow the browser to asynchronously load CSS and JavaScript?
I have this in my head tag:
<link rel="preload" href="http://zoidstudios.com/assets/css/main.css" as="style" onload="this.rel='stylesheet">
<noscript><link rel="stylesheet" href="http://zoidstudios.com/assets/css/main.css"></noscript>
And this at the bottom of my html file :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://use.fontawesome.com/eb515f50a5.js"></script>
<script src="http://zoidstudios.com/assets/js/functions.min.js"></script>
<script src="http://zoidstudios.com/assets/js/loadcss.min.js"></script>
<script>
loadCSS( "http://zoidstudios.com/assets/css/main.css" );
</script>

Have you looked into loaders like RequireJS or webpack? Most loaders will support CSS natively and/or offer CSS plugins to load CSS, JS, etc. asynchronously all while ensuring dependencies. If you have many files to load I would suggest looking into a loader of your preference.

The problem is not with the CSS. If PageSpeed thinks your page load is bogged down, it's probably the result of all those <script> tags at the end of your <body> tag. Just because they are placed in the body tag does not mean they are asynchronous.
You can leave them all in the <head> tag. You can include the attribute async or defer to get asynchronous loading: have a look at this explanation.
So, something like this should do:
<script
src="http://zoidstudios.com/assets/js/functions.min.js"
defer>
</script>
Note that if any of those scripts expect the DOM to be parsed (i.e., they expect certain elements to exist already), you should use defer instead of async, as explained in the linked article. Or, you can leave those in the <body> tag, and use async.
Update
If my hypothesis is correct (that PageSpeed does not support rel='preload' on <link> tags), notice that the documentation linked in your question advises you to
include the loadCSS script, as well as the loadCSS rel=preload
polyfill script in your page (inline to run right away, or in an
external file if the CSS is low-priority)
You may be able to eliminate the final warning by using the recommended polyfill.
The general problem, "how do I load CSS asynchronously?" has been asked and answered many times on StackOverflow, as I'm sure you know!

Related

How to extract unused CSS/JS (not just purge) into a separate file?

My goal is to eliminate render-blocking CSS and JS on a website.
Google suggests to identify the used CSS/JS via coverage, and move that code from the render-blocking URL to an inline script tag in your HTML page. When the page loads, it will have what it needs to handle the page's core functionality.
For example for core CSS:
<style type="text/css"></style>
The rest of the CSS can then be loaded asynchronously via preload.
<link rel="preload" href="non-core-styles.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="non-core-styles.css"></noscript>
I have come across Purgecss that can remove unused css.
purgecss --css bootstrap-grid.min.css --content index.html --out dist/
But I would rather like to extract the unused CSS in order to load them async via preload as explained above to avoid any issues with the website itself.
How can this be achieved with Purgecss or any other tool, please?
Same goes with javascript. The core can be loaded like this:
<script src="app.js"></script>
While the non-critical parts can be loaded async like this:
<script src="app.js" async></script>
But is there a tool that can extract the unused JS from my site though?
Thanks
Take a look at https://github.com/pocketjoso/penthouse for extracting the 'critical' CSS for a page, this will then go in your <style type="text/css"></style> tag.
I'd recommend then including all of your CSS in the CSS file via a link tag. This will mean it's the same on each page and can be cached by the browser.

What's the best (fast) way to load javascript in different pages?

What's the best way to load fast javascript in different pages ? Should my custom javascripts go separate for each page or all custom javascripts should be present only in 1 common custom.js file and include this file in footer ?
require_once($header);
include_once($page2.php);
require_once($footer);
<script src="js/custom-page2.js"></script>//separate for each page
require_once($header);
include_once($page1.php);
require_once($footer);
<script src="js/custom-page1.js"></script>//separate for each page
OR
//in footer.php include all js in 1 file
<script src="js/all-custom.js"></script>
If all pages share the same scripts using one script will be better.
If they use different scripts you can cut out what each page DOESN'T need and save on HTTP requests.
Or a mixture of the two.
So...it depends?
Basic rule: If you don't need it, don't load it.
I advise you to create your html page by including in this order :
HTML wrap all
Head (with style in one page for example)
Body with:
Javascript modules
Main HTML DOM
Javascript DOM modifiers and launchers
Same like this :
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script type="text/javascript" src="modules.js"></script>
<div class="body"></div>
<script type="text/javascript" src="functions.js"></script>
</body>
</html>
it's good idea to put all js in header (browser will not render page until all header files are loaded, at least in theory).
browser (proxy etc) will cache your js, so it's not going to be fetched from your site on every request. browser will only check if file has changed.
in most cases browser will keep single connection for all requests, however it still has to ask for every single js file if it hasn't changed. i keep js logic in small seperate files during development, but then i merge them for production.

Mimicking Browser's Script Loading and Executing Behaviour in Javascript

If I have,
<script src="jquery.js" ></script>
Then any script after this will allows you to use jQuery($) variable. I need to mimic this behavior in javascript. What I need that add my script file,
<script src="myscript.js" ></script>
which will load jquery.js using javascript and any script after this tag will allow you to use jQuery($) variable. I have no control beside myscript.js file. So I need to make sure that jquery.js must be loaded before allowing the browser to run/execute/render next tags.
What you are trying to achieve is not possible. When loading scripts dynamically you need to use callbacks to ensure that those scripts are loaded and use them only inside those callbacks. You cannot have sequential <script> tags in which one of the scripts loads dynamically some other scripts such as jquery and have subsequent scripts use jQuery. Browsers load script tags sequentially and guarantee that they will be loaded in the same order, but once you start injecting dynamic scripts into the DOM the only way to ensure proper load is to use callbacks. Take a look at the following article for more details.
Splitting it up in two parts should work:
index.html:
<html>
<body>
<script src="myscript.js"></script>
</body>
</html>
myscript.js:
document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>');
document.write('<script src="myprog.js"></script>');
myprog.js:
$(function(){
alert('jquery ready');
});

Google Audit Question

The following external CSS files were
included after an external JavaScript
file in the document head. To ensure
CSS files are downloaded in parallel,
always include external CSS before
external JavaScript. 1 inline script
block was found in the head between an
external CSS file and another
resource. To allow parallel
downloading, move the inline script
before the external CSS file, or after
the next resource.
My HTML is:
<head>
<link rel="Stylesheet" href="gStyle.css" />
<script type="text/javascript" src="gMain.js"></script>
<script type="text/javascript" language="javascript">
// Your chart object(s)
var myChart;
// Function to hold all chart creation
function initCharts() {
myChart = new ganttChart("chart1");
myChart.gAddBar("Dynamic!", "22/3/2010", "3/4/2010");
myChart.gLoadData("Going to the shop*4/3/2010*19/3/2010*Watching TV*9/3/2010*23/3/2010*Watching TV*1/3/2010*23/3/2010*Watching TV*18/3/2010*28/3/2010*END INPUT*1/3/2010*9/3/2010");
myChart.gDraw();
myChart.gChangeBarColour(1, "#dd2200");
myChart.gChangeBarColour(2, "#9900ee");
myChart.gChangeBarColour(3, "#00dd00");
myChart.gChangeBarColour(4, "#ffbb00");
myChart.gChangeBarColour(5, "#00aa99");
}
</script>
</head>
<body onload="initCharts()">
<div id="chart1" class="gContainer">
</div>
<div id="db"></div>
</body>
Is it getting confused between the body inline script?
Inspect the page elements. Probably your Chrome extensions are dynamically adding scripts to the page in HEAD.
I think that when javascript is downloaded the browser must wait to get it all and then run it - this stops it going to the next line directly and getting it. I guess styles all get downloaded and then computed down to inheritance position and importance etc...so they can download in parallel.
This kind of thing is hard to regulate in a CMS with components that load their own style and js.
For me, Google Analytics library inserted scripts before the rest of mine.

Order of loading external CSS and JavaScript files

I have a third party application that loads many css and javascript files, and I now want to optimize this by concatinating all the javascripts into one file, compressed by the yuicompressor, but ... when we have a mix like:
<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
<link rel="stylesheet" href="style1.css" type="text/css" />
<script type="text/javascript" src="script3.js"></script>
<script type="text/javascript" src="script4.js"></script>
Does it matter that there's a css in the middle here? Should I concatinate and yuicompress the 4 javascripts and load them before the CSS or after?
Check out Yahoo's Best Practices for Speeding Up Your Web Site, they recommend loading your css first (preferably in the header), and your js last (after all the content in the body). Google's best practices also recommended loading CSS first.
It depends. If all the JS only works on DOM ready, the order is unimportant. However, if there is any in-line javascript that changes CSS styling of DOM elements, then you'll have issues.
More practically, you should probably put the CSS first so there is less time where the user needs to experience unstyled content.
It doesn't matter, although if loading takes a while, the user might see his page change appearance and wonder why. I'd put the CSS files first to have the style definitions in place before any DOM manipulation, most likely minimizing the visible change as the page loads, but it doesn't really matter in the end.

Categories

Resources