JavaScript terminating all scripts running without throwing errors - javascript

In a company website, I have a page embedding JavaScript in such fashion:
<html>
<head>
<link rel="stylesheet" href="...">
<link rel="stylesheet" href="...">
<script src="..."></script>
<script src="..."></script>
<script>
...
</script>
<script>
/*
* My block
*/
</script>
<script>
...
</script>
<script src="..."></script>
</head>
<body>...</body>
</html>
The page is semi-managed by other teams in the company. The <script>'s before My block are hardcoded to load some of the prerequisite company-wide scripts. One of those scripts is jQuery. I can't change any of them because they are managed by another team. Due to some reasons, those scripts fail to load randomly sometimes. (Response codes can be 400, 404, 500, etc)
The scripts below My block have dependencies on the scripts above My block. So if the scripts on the top fail to load, the scripts at the bottom will throw out a lot of errors.
Inside My block, I am hoping to add a check to see if those scripts are loaded and running. (May be to check against jQuery?) If they are not loaded, I want to terminate all the loading/running of the scripts after My block, so the page will display a user-friendly message and doesn't throw a bunch of errors.
I wonder if this is possible?

Related

HTML page loads slowly unless I omit one of three linked static files

In the page's head tag I use 3 external files (CSS, Font, jQuery Library):
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet"> <!-- Poppins font -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
As I use all the 3 - Page loads very slow. If I omit one of them (no matter which one) - page loads immediately. Why is that?
This is because the scripts are being loaded synchronously one after the other.
How to make them load faster?
If there is no dependency between the scripts and links load them asynchronously:
Asynchronously loading JS scripts
For that you can use async attribute.
From the docs:
When present, it specifies that the script will be executed
asynchronously as soon as it is available.
Example:
<script src="demo_async.js" async></script>
Like #IvanS95 mentioned below - you can also use defer.
Asynchronously loading CSS links
You can use preload.
Fro the docs:
Resources loaded via are stored locally in the
browser, and are effectively inert until they’re referenced in the
DOM, JavaScript, or CSS. For example, here’s one potential use case in
which a script file is preloaded, but not executed immediately, as it
would have been if it were included via a tag in the DOM.
An example:
<link href="style.css" rel="preload" as="style">
Try loading the js file at the end.
</head>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<link href="https://fonts.googleapis.com/css?family=Poppins" rel="stylesheet"> <!-- Poppins font -->
</head>
<body>
...
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
My recommendation would be to run your site against - https://www.webpagetest.org/ excellent resource.
Also, I would cache the data for 365 days that way they do not have to call your external scripts again.
To learn about caching check out this site - https://www.codebyamir.com/blog/a-web-developers-guide-to-browser-caching
And you can always use your F12 Browser tools to see the waterfall effect of loading all the elements of your Web page.

How to use rel="preload" as="style" or as="script" or Better method for page speed

i am trying to reduce my webpage load time . When i am searching i come to this point preload css and javascript .
So i am trying to implement this in my html page please see my html code before and after implementation
before
<html>
<head>
<link href="http://fonts.googleapis.com/css?family=lato:400,100,200,300,500%7COpen+Sans:400,300,600,700,800%7COswald:300,400,700" rel="stylesheet" type="text/css"> ...........
</head>
<body>
html contents
<script src="assets/js/jquery-1.12.4.min.js" type="text/javascript"></script>
</body>
</html>
After implementation i change like this
<html>
<head>
<link rel="preload" href="http://fonts.googleapis.com/css?family=lato:400,100,200,300,500%7COpen+Sans:400,300,600,700,800%7COswald:300,400,700" as="style">
<link rel="preload" href="assets/js/jquery-1.12.4.min.js" as="script">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=lato:400,100,200,300,500%7COpen+Sans:400,300,600,700,800%7COswald:300,400,700">
</head>
<body>
html contents
<script src="assets/js/jquery-1.12.4.min.js"></script>
</body>
</html>
But i can't notice any increase in speed . So please help to make this in correct way
i read the following article
https://developer.mozilla.org/en-US/docs/Web/HTML/Preloading_content .
But i can't figure out . Please help .
Or is there is any better method for page speed ?
Why this doesn't work
Preloading resources that are loaded directly in the HTML is useless. This is because the browser reads the preload at the same time as the actual resource reference.
Preloading is useful to reduce the length of your request waterfall.
Imagine the following situation:
style.css
body {
background-image: url(myimage.png);
}
index.html
<html>
<head>
<link rel="stylesheet" href="style.css" />
</head>
<body>
</body>
</html>
The process of loading the above page consists (roughly) of the following steps:
Download index.html
Parse the HTML file
Because of the link tag, download style.css
Parse the CSS file
Because of the background-image, download myimage.png
Parse the image and display it on the screen
This means your request waterfall is index.html -> style.css -> myimage.png.
By adding a preload for myimage.png the browser can download the image earlier, so your request waterfall becomes:
index.html +-> style.css
+-> myimage.png
Instead of 3, it is now only 2 requests long, which means faster load times.
What else can you do to improve (perceived) page load times?
Some common ways are:
Minify your assets (JavaScript, stylesheets)
Ensure your server has compression enabled for static assets
Only load resources actually required on page load first, then load other scripts later (like those for user interactions).
But to get a better overall view of the things you can improve you can use the Chrome Audit system (Lighthouse).
https://developers.google.com/web/updates/2016/03/link-rel-preload
See the above article link. I saw the link shared above. Preload never makes the page load the page fast. It only gives the priority to the files which is declared rel="preload" to load very early as the page loads up. You can read the article again Also the article shared by me. It will say the same.
You will need other methods to load the page fast. This method will not be helpful. There are few methods listed below you can use to make page load faster.
You can minify css and js files which will load very very fast than normal file.
You can minify script and css files from (https://www.minifier.org/) here.
Avoid external links of css and js files
Avoid spaces and Newlines in code.
Use compressed images which will also load faster.
Enable Caching.

Where is the ideal place to load javascripts in html? [duplicate]

This question already has answers here:
Where should I put <script> tags in HTML markup?
(21 answers)
Closed 2 years ago.
I understand inline javascripts scattered through html code like the following example is bad
<html>
<head>
</head>
<body>
<p> Foo <script></script></p>
</body>
</html>
However, after coding for a while, understanding that loading Javascripts at the end of the document is the best way to go. I do see a lot of the sites that conform to loading scripts at the end of their document, do so in the following manner :
<html>
<head>
</head>
<body>
<p> Foo </p>
<script></script>
</body>
</html>
What is not made clear, is why not :
<html>
<head>
</head>
<body>
<p> Foo </p>
</body>
<script></script>
</html>
.. as this is outside the body tag which means that the body (in theory) can process faster and still load your scripts before finalizing on </html>.
Or even this :
<html>
<head>
</head>
<body>
<p> Foo </p>
</body>
</html>
<script></script>
Each variation will have (in theory) different performance results, and/or may break functionality in the page depending on the script contents of course.
Of the above formats, which one is the ideal place to load javascripts that would have the highest performance gain without breaking html ?
The best place at the end of the body tag, like
<html>
<head>
</head>
<body>
some html body tags
.
.
.
<script> external or inline </script>
</body>
</html>
If you do like so, then the html will load quicker and main pros is that all your ids and classes will get assigned otherwise sometime if you put script above html, then there might be a chance that you try to get an element by id that is not yet assigned in DOM
[UPDATE]
Here is an example code that Bootstrap is using in their own website: http://getbootstrap.com/getting-started/
you can find this code under Basic template Heading:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<h1>Hello, world!</h1>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- Include all compiled plugins (below), or include individual files as needed -->
<script src="js/bootstrap.min.js"></script>
</body>
</html>
As noted here, the script tag won't validate outside of the body or head tags. However, you want to place it as far down as possible, so that the rest of the page loads first, to avoid errors. This leaves us with the place furthest down, but inside the body and head tags: just before the closing body tag.
<html>
<head>
</head>
<body>
<p> Foo </p>
<script></script>
</body>
</html>
If you know how the browsers work it will be easy to know where to put it.
First of all it's invalid to include your script after the body or the html element. Only comments and the closing tag for html are allowed after the body. Some browser will do recovery but you shouldn't depend on that.
You may include it any where in the body or the head but you should know that script take the browser attention may be for while and I will stop rendering the dom. That's very bad for user experience so the best place to include it just at the end of the body element.
Like in the example :
<html>
<head>
</head>
<body>
<p> Foo </p>
<!-- ... -->
<script></script>
</body>
</html>
One more thing if you include the script at the top of the page and that script will manipulate the dom that may cause an error if the dom isn't ready yet. The script searching for element which is not exist yet. And it will be very confusing when it runs at time and it doesn't run in another time. You may check the answers for similar questions here and here
How browsers work: As you can see from here, most of the browsers parsing the html elements top to bottom in elements tree hieararchy.
So, when you put a script just before </body> tag, make sures that most of the elements has been loaded or at least parsed. Or, you just need to wait for document.readyState.
Also, by putting your script below </body> tag is semantically not good. But, you can do it and it won't make a difference for the performance.
Important thing to note is the following:
If you put the script in the head tag HTML page rendering is blocked until the script is downloaded.
The more scripts you will put there the slower your page will load.
That’s why an advanced approach is to put the scripts at the bottom of the BODY, and in this case the user can start interacting with a page before the Javascript has Loaded.
You will put the scripts in HEAD only if they MUST be available before the page is shown.
Best way to load your java-script at the end of body tag, but in some case when you use third party script, it need be load before control initialize.
<html>
<head>
</head>
<body>
...........
<script></script>
</body>
</html>
JavaScript is a render blocking resource. So when browser is parsing HTML document and encounters script in between, the control is passed to js engine. Which runs the script and returns the control to browser again.
<html>
<head>
<script src="/main.js" />
</head>
<body>
<script>
//some inline script
</script>
</body>
</html>
So when broswer encounters the script tag in header, it passes the control to js engine. Now beacuse the script is being loaded from network, js engine will wait for script to load. After that it will be executed. Then document parsing will resume. (Inline script in head would have worked faster as network delay would be avoided)
Same goes for inline script. Situation gets complex if CSS is also present along with javascript. If a CSS is also being loaded from network in the head, js engines will wait for it too. So there are 2 dependencies now.
So it is best to add js at the bottom and CSS at top generally (to avoid Flash of Unstyled Content).
A good read for the same is present here :
Critical Rendering Path

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.

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.

Categories

Resources