How to load external JS libraries for the whole project - html

How do you load an external library so that it is available all over the project?Say for example I have the below:
<!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>Starter Template for Bootstrap</title>
<!-- Bootstrap core CSS -->
<link href="../public/css/bootstrap.css" rel="stylesheet">
<!-- Font Awesome core CSS -->
<link href="../public/css/font-awesome.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../public/css/style.css" rel="stylesheet">
</head>
<body>
<p>This is a test</p>
<!-- Bootstrap core JavaScript-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="../../assets/js/vendor/jquery.min.js"><\/script>')</script>
<script src="../jsLib/bootstrap.js"></script>
</body>
</html>
So this includes the jQuery, Bootstrap, font-awesome and my personal stylesheet as you can see.
Question: What if someone goes to another page in my site for instance: /profileSettings.html
Will I have to load all the libraries again?
Sorry if this is a simple question but I am completely new to front-end development.
Thanks in advance

As your code grows in size, you'll start using more sophisticated frameworks that may use something along the line of an MVC setup. Some of these frameworks allow you to define multiple "views"(think of them as HTML files for now) that are called from a single HTML file(say the index file).
For those aware of AngularJS, i'm referring to writing Angular UI views and the <ui-view> tag.
This will allow you to have your dependencies in a single file, and the other pages just load from this page.
More importantly.
I'm surprised noone has mentioned the use of require-js or other loaders.
It's particularly useful in cases where you have multiple JS dependencies, and multiple controllers in javascript.
Definitely check out loaders such as require-js

Each page is completely independant of every other page.
If you want a script to run on any given page, it has to be explicitly loaded into that page.

Yes. U have to include the required lib in each file if it is normal file without any framework.

You have to include the scriipt in every page because even thought it is a website, every page works seperately from another. All you need is a <script></script> tag.

Yes, if you look each page as separate page. You need to include it in every page.
But if you have a master page, then we can inherit the same from master page so, no need to add the Codes/Script again.
A cool option.
Load one JavaScript file (JS File) for every page. Then load all the JS File using that JS File as you like.
Example
var Device = {
Device_Type: 'Desktop',
//Scripts to be loaded in master page
Common_Scripts: [
'/SiteAssets/Bar.js',
],
//CSS to be loaded in master page
Common_CSS: [
'/SiteAssets/nav.css',
],
//to get device type
Get_Device_Type: function () {
var Getdevice = detect.parse(navigator.userAgent);
if (Getdevice.device.type != null) {
Device.Device_Type = Getdevice.device.type;
Device.Process_Device_Files(Device.Device_Type);
Device.Process_Common_Files();
Device.Process_Common_Scripts();
} else {
console.log("Detected Device type :" + Device.Device_Type)
}
},
//to load device based css files
Process_Device_Files: function (File_Type) {
File_Type = File_Type.toLowerCase();
$('head').append(
'<link rel="stylesheet" title="' + File_Type + '" href="announcement.css">'
);
},
//To load css files to be loaded in master page
Process_Common_Files: function () {
_.each(Device.Common_CSS, function (eachfile) {
Common.appendfile("css", eachfile);
});
},
//To remove previously loaded device files
Remove_Device_Files: function () {
$('link[title="tab"]').remove();
$('link[title="Mobile"]').remove();
$('link[title="desktop"]').remove();
},
//To load scripts to be loaded in master page
Process_Common_Scripts: function () {
_.each(Device.Common_Scripts, function (eachfile) {
Common.appendfile("script", eachfile);
});
},
}
$(document).ready(function () {
console.log('Render device based files')
Device.Remove_Device_Files();
Device.Get_Device_Type();
});
Usage
(Copy the Above code after Example until usage and paste it into a notepad and save it as device.js. Then include to the page. Then add the necessary JS to this codes. Sample files are already in the codes)
// Dependencies
https://github.com/darcyclarke/Detect.js?files=1

Related

Auto fill code from txt file to every html pages? import code from txt to all html pages via single code

I no longer want to always write the same code for every html file. Is there a way to make below code available on the all html pages.
<script async src="https://www.googletagmanager.com/gtag/js?id="></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', '');
</script>
<meta charset="UTF-8">
<link rel="icon" href="icon.png">
etc...
I mean, for example, copy code from head.txt on every html page. This will allow me to not write the same snippet of code on all the pages.
Your question is very difficult to understand, but I will try.
Documents are connected using
<link rel = "import">
:
<head>
<link rel = "import" href = "/ path / to / imports / stuff.html">
</head>
The URL specified is the import location. To use import from another domain, its location must allow cross-domain resource sharing (CORS):
<! - Resources on other origins must be CORS-enabled. ->
<link rel = "import" href = "http://example.com/elements.html">
Note: browsers ignore repeated requests to the same URL. This means that from one address only one download will be performed no matter how many connections on the page

Use Nivo graph lib in a single HTML page (React)

I have a single HTML page with React (build manually without ANY tools, just a text editor).
This page is working correctly. Now, I would like to add a PIE Chart with NIVO lib.
When I add the script (CDN) I got the following error in console:
exports is not defined
I can solve this by creating a fake exports var = {} (is that a good solution ?)
But then I have a new error:
require is not defined
Do that means the CDN link from NIVO is incorrect ? How to solve this ?
Alternative: I am open to use another lib working with React. But I want to only use CDN links and a text editor to achieve that.
Full HTML file:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>Batch stats</title>
<script>let exports = {};</script>
<script src="https://unpkg.com/#babel/standalone/babel.min.js"></script>
<script crossorigin src="https://unpkg.com/react#16.7.0/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom#16.7.0/umd/react-dom.production.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/#nivo/pie#0.61.1/dist/nivo-pie.cjs.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
function Page(props) {
return (
<div>
<h1>Hello World</h1>
<div>How to add a PIEChart ?</div>
</div>
);
}
ReactDOM.render(<Page version="v3"/>, document.getElementById('root'));
</script>
</body>
</html>
Thanks
Nivo do not support it.
you should use the UMD build, however, you'll need a bunch of extra
dependencies, including D3 packages which are using modern JS
features.
https://github.com/plouc/nivo/issues/959

Is Semantic-UI + ReactJS available for a cave man?

I am a cave man in terms of web ui - I like it all without npm/nodejs and other nice infrastructure. I want it all in text files like in old days: include/link stuff from/to a HTML page and it's done. Is such cave approach possible for semantic-ui+ReactJS combination, meaning to have no npm/nodes/other server code for my front end to work?
You can always skip over using npm/nodejs/bundling by putting the 'packages' you want as script tags in the header of your html page. This still allows you to grab the extra libraries you want but means you don't need bundling and transpiling if you want to keep it simple. Like you mentioned, this is the way that used to be the standard and it still works just fine.
As an example, here is how to use react without a npm: JSBIN
Your HTML would look like:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://unpkg.com/react#15.1.0/dist/react.js"></script>
<script src="https://unpkg.com/react-dom#15.1.0/dist/react-dom.js"></script>
</head>
<body>
<div id="root"></div>
</body>
</script>
</html>
Then the JS code for using react could look like:
const Child = () => <div>Child</div>
const Parent = () => {
return (
<div>
Parent
<Child />
</div>
)
}
ReactDOM.render(
<Parent />,
document.getElementById('root')
);
This answer is specifically for if you want to skip npm and bundling all together. I would definitely recommend checking out create-react-app if you are ok with having it do your config/bundling/transpiling for you.
I think the answer is yes, that is if I am understanding your question. One of the ways you can use react (and any css lib, like Semantic UI), is to generate a static build that can be hosted very simply on any static hosting service (all text files, like in old days). however, it is common to use npm and node during development.
this is a useful tool to get started: https://github.com/facebookincubator/create-react-app

Installing Jasmine failing

I'm trying to get Jasmine to work on my website. This is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Jasmine Spec Runner v2.1.3</title>
<link rel="stylesheet" type="text/css" href="/Content/css/jasmine.css" />
<script src="/Scripts/UnitTesting/boot.js"></script>
<script src="/Scripts/UnitTesting/jasmine-html.js"></script>
<script src="/Scripts/UnitTesting/jasmine.js"></script>
<!-- include source files here... -->
<!-- include spec files here... -->
<script src="/Scripts/UnitTesting/HelloWorldSpec.js"></script>
</head>
<body>
</body>
</html>
And HelloWorldSpec.js:
function helloWorld() {
return "Hello world!";
}
describe("Hello world", function () {
it("says hello", function () {
expect(helloWorld()).toEqual("Hello world!");
});
});
When I load this page, I get:
ReferenceError: jasmineRequire is not defined
ReferenceError: describe is not defined
I thought I got the reference to the JS files wrong. But when I look at the page source, and click on one of the js links, for example, "/Scripts/UnitTesting/boot.js", I see the source code, so it appears the files are loaded succesfully. What's going wrong here?
The boot.js file should be loaded after jasmine.js and jasmine-html.js Otherwise what would it boot? The correct order that you should include the files is:
jasmine.js
jasmine-html.js
boot.js
http://jasmine.github.io/2.0/boot.html
Starting with version 2.0, this file “boots” Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project’s specs. This file should be loaded after jasmine.js and jasmine_html.js, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project.

Optimizing above-the-fold CSS

I want to fix the "Eliminate render-blocking JavaScript and CSS in above-the-fold content" requirement for better PageSpeed Insights score but I'm not quite sure what the best approach to this problem is.
How can I best balance the page load for new visitors and returning visitors?
When should I load my CSS asynchronously, when not?
Should I maybe only inline CSS for small screens?
Relevant presentation: Optimizing the Critical Rendering Path
Example
Since inlining lots of CSS leads to slower page loads on subsequent visits, I could serve different versions for recurring visitors based on a cookie. For detecting above-the-fold CSS I could use the bookmarklet from this article: paul.kinlan.me/detecting-critical-above-the-fold-css/
For new visitors:
<!DOCTYPE HTML>
<html>
<head>
<title>New Visitor</title>
<style><!-- insert above the fold css here --></style>
<noscript><link rel="stylesheet" href="style.css"></noscript>
</head>
<body>
<!-- insert content here -->
<script>
// load css
var node = document.createElement('link');
node.rel = 'stylesheet';
node.href = 'style.css';
document.head.appendChild(node);
// set cookie
var exp = new Date();
exp.setTime(exp.getTime() + 3600 * 1000);
document.cookie = 'returning=true; expires=' + exp.toUTCString() + '; path=/';
</script>
</body>
</html>
For returning visitors:
<!DOCTYPE HTML>
<html>
<head>
<title>Returning Visitor</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<!-- content here -->
</body>
</html>
Any problems with this approach?
There is such a thing as over-optimizing. Your example approach adds unneeded complexity. What you should be looking at is a minimal stylesheet for the head section that will make everything above the fold make sense and conform to the design and layout (but not necessarily respect it 100%).
For the rest of the page just load the rest of the CSS at the end of the page and you should be fine. If what matters to you is above the fold, then so does the first CSS you load. Everything else can be delayed.