I am using font-awesome 5.3.1 css and adding to my page like this:
<script type="text/javascript">
var shared = {};
shared.css = ["https://use.fontawesome.com/releases/v5.3.1/css/all.css"];
(function () {
var container = document.querySelector('head');
shared.css.forEach(function (href) {
var css = document.createElement('link');
css.href = href;
css.rel = 'stylesheet';
css.type = 'text/css';
document.getElementsByTagName('head')[0].appendChild(css);
});
})();
</script>
This is at the very end of the body yet when I run my page on PageSpeed it complains of the render blocking css related to font awesome.
How do I fix this? I tried font awesome cdn but it only support 4.7 and there is no new version on it.
You can execute this Javascript after the page loads completely. See follow:
document.addEventListener('DOMContentLoaded' (){
/*** Put the code here **/
})
This will ensure that script is loaded once the Document is loaded fully.
Related
I am using the following script to apply the stylesheet only if the class .item-label is not present on the page. I does not seem to work. Any ideas where my script is wrong? It seems the script is ignoring the class: .badge-icon icon-template... It doesn't matter if it is present or isn't present. I have the script loading at the bottom of the page.
<script>
if(!document.querySelector('..badge-icon icon-template')){
var link_el = document.createElement('link');
link_el.rel = 'stylesheet';
link_el.href = 'https://sub.domain.com/tester1.css';
document.head.appendChild(link_el);
}
</script>
So,
it seems superfluous to remind you that there may be infinite reasons why your code, apparently correct, does not work.
Assuming that your page does not contain errors in the HTML, or in some script, there could be two potential causes:
Your script is executed before the document is loaded, or the css file is not downloaded as it is already in the browser cache or all things.
try adding this script and then if the problem persists could you add the browser console output to the question?
<script>
document.addEventListener("DOMContentLoaded", function(){
if(!document.querySelector('.badge-icon icon-template')){
var noCache = '?' + new Date().getTime(); // add timestamp to url to force file upload
var link_el = document.createElement('link');
link_el.rel = 'stylesheet';
link_el.href = 'https://sub.domain.com/tester1.css' + noCache;
document.head.appendChild(link_el);
}
});
</script>
Just Add type also:
var link_el = document.createElement('link');
link_el.rel = 'stylesheet';
link_el.type = 'text/css';
link_el.href = 'tester1.css';
document.head.appendChild(link_el);
Check it here
Just put your code just before the ending </body> tag this should ensure the document is loaded
<script>
// DOM available
</script>
</body>
I need am essentially making a piece of code that will inject my own code onto the webpage.
Due to me being limited on my ipad I am using bookmarklets so here it is:
I am using this code to call on a js file that will create the button
javascript: (function () {
var jsCode = document.createElement('script');
jsCode.setAttribute('src', 'http://path/to/external/file.js');
document.body.appendChild(jsCode);
}());
The button I want to make will need to be created with the code shown below:
<button id=“supermoneybutton” onclick=“moneyget()”>get money</button>
Then I need to add a link to an external css file.
I have the file for the css, I just need help making the js work, the injection code already works it just shows my method for injection.
In your JS code that dynamically creates the button, you should add the event handler there too:
(function () {
var button = document.createElement('button');
button.id = 'supermoneybutton';
button.addEventListener('click', function (e) {
// Do Stuff
moneyget();
});
document.body.appendChild(button);
// Add CSS File
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = '/path/to/cssfile';
link.type = 'text/css';
var linkRef = document.getElementsByTagName("link")[0];
linkRef.parentNode.insertBefore(link, linkRef);
})();
var cssId = '../../../css/export-csv.css';
if (!document.getElementById(cssId))
{
var div = document.getElementsByTagName('div')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.media = 'all';
div.appendChild(link);
}
I want to import a CSS file named 'export-csv.css' in my js file but I am not able to do that. Thanks in advance
href is used to reference the id and move the link from one place to another where its not assign. If you want to assign any value make it as "ID or class" then it will easy for you to call in javascript.
Try document.getElementsByTagName( "head" )[0].appendChild( link ); instead of
var div = document.getElementsByTagName('div')[0];
div.appendChild(link);
and check that css file path is correct , it should resolve the issue. More details at How to load up CSS files using Javascript?
function loadCSS(filename){
var file = document.createElement("link");
file.setAttribute("rel", "stylesheet");
file.setAttribute("type", "text/css");
file.setAttribute("href", filename);
document.head.appendChild(file);
}
//just call a function to load a new CSS:
loadCSS("path_to_css/file.css");
So the following code should do the trick:
var aCSS=document.createElement('link');
aCSS.setAttribute('rel', 'stylesheet');
aCSS.setAttribute('type', 'text/css');
aCSS.setAttribute('href', 'someCssName');
document.getElementsByTagName('head')[0].appendChild(aCSS);
You can also load it in a blocking way by using document.write. The issue with loading CSS dynamically is that it degrades the user experience a lot, as the user will see a flickering of things at best case, and two different stories of the same element at worst case (slow css loading). I am not sure what is the use case, but please be careful when loading CSS dynamically.
I would suggest you using gulp or grunt to combine your css into one minified file and this would be a better approach IMO.
A few pieces are wrong here.
Your cssId looks like a file path. It could conceivably be an id but I doubt it.
There is no href. Since you are using an external stylesheet (<link> tag), your code needs to give the stylesheet an href, otherwise the browser will have no idea where to go fetch the styles from.
Inserting a stylesheet into a div is strange. It is more appropriate to put them in the head. While HTML5 does allow you to be a rebel, there are far more downsides than upsides to breaking this rule.
Here is a fixed example:
var cssId = 'some-legitimate-id';
if (!document.getElementById(cssId))
{
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.media = 'all';
link.href = '../../../css/export-csv.css';
document.head.appendChild(link);
}
Try this:
var div = document.createElement("div");
In place of:
var div = document.getElementsByTagName('div')[0];
Might be unable to find the div[0].
I've been working hard to achieve 100/100 on Google Pagespeed (https://developers.google.com/speed/pagespeed/insights/) but I keep getting hungup when trying to use Javascript to download CDN based files. I get 'CAUTION: Provisional headers are shown.' and I assume it's blocking this kind of call for security reasons but I'm stuck.
I can call script files asycn like this, which Google likes:
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js" async></script>
But what am I to do about the CSS files? If I call it the normal way:
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
Google complains and says I have a 'blocking CSS resources'.
Here's a copy of the code I've been trying to use so far:
var headID = document.getElementsByTagName("head")[0];
var cssNode = document.createElement('link');
cssNode.type = 'text/css';
cssNode.rel = 'stylesheet';
cssNode.href = '//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css';
headID.appendChild(cssNode);
Anyone have any suggestions?
Here is the code I ended up creating to handle loading both css and js files async at the same time. Just put this at the bottom of your HTML before you closing tag and edit the loadjscssfile() calls as necessary.
<script>
/* Beginning of async download code. */
window.onload = function(){
function loadjscssfile(filename, filetype) {
if(filetype == "js") {
var cssNode = document.createElement('script');
cssNode.setAttribute("type", "text/javascript");
cssNode.setAttribute("src", filename);
} else if(filetype == "css") {
var cssNode = document.createElement("link");
cssNode.setAttribute("rel", "stylesheet");
cssNode.setAttribute("type", "text/css");
cssNode.setAttribute("href", filename);
}
if(typeof cssNode != "undefined")
document.getElementsByTagName("head")[0].appendChild(cssNode);
}
loadjscssfile("//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css", "css");
loadjscssfile("//fonts.googleapis.com/css?family=Open+Sans:300&subset=latin,cyrillic-ext,latin-ext,cyrillic,greek-ext,greek,vietnamese", "css");
loadjscssfile("/css/style.css", "css");
loadjscssfile("//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js", "js");
loadjscssfile("//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js", "js");
};
/* End of async download code. */
</script>
Google provides a good explanation of this here:
https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery
It seems like they want you to inline CSS that is crucial to the page's initial display. Then load secondary CSS after. Since the bootstrap CSS is one large mix, I think it'll be non-trivial to separate crucial/non-crucial for your page.
Perhaps you can inline some duplicate CSS that exists in bootstrap.css
I'd suggest you to inline the styles for the critical path (above the fold):
https://github.com/addyosmani/above-the-fold-css-tools
https://github.com/addyosmani/critical
Then load the other css async:
https://github.com/filamentgroup/loadCSS/
I'm new to Javascript (but not HTML or CSS) and am trying to use this script by Lalit Patel to detect whether a font is installed on the user's system, and if not, to serve a modified style sheet. I've been successful in getting the first part to work: I uploaded the fontdetect.js file, called it in my header, then pasted this before the end of my body tag:
<script type="text/javascript">
window.onload = function() {
var detective = new Detector();
alert(detective.detect('Courier'));
};
</script>
(With Courier used as an example.) This causes an alert to pop up on page load telling me whether a font is installed, and works beautifully. But I don't know how to get the script to, instead of triggering an alert, grab a different stylesheet. This seems like basic stuff but I just can't find the specifics anywhere, even though I've been plowing through Javascript tutorials. Any guidance would be greatly appreciated!
If any more specifics are needed: If a user doesn't have the custom font installed or has custom fonts turned off entirely, I'd like to, using CSS change the size/spacing properties of the text so that the fallback font is able to fit in the same space.
var detective = new Detector();
if (!detective.detect('Courier')){
var s = document.createElement('link');
s.rel = 'stylesheet';
s.type = 'text/css';
s.media = 'all';
s.href = '/link/to/alternative/stylesheet.css';
document.getElementsByTagName('head')[0].appendChild(s);
}
Guessing something like that. if .detect() fails, it will dynamically create and insert a stylesheet in to the page. If you encounter problems, you can also use .setAttribute() off of the s element.
You can use JS to add a stylesheet to the website:
var detective = new Detector();
if (!detective.detect('Courier')){
document.createStyleSheet('location/stylesheet.css');
}
else
{
document.createStyleSheet('location/otherstylesheet.css');
}
So you could do a check to see if the Dectector returns true, if not load one style, if it does then load the other.
After trying all the methods presented, this is the one that worked for me (from this answer, but it's really a mix of the two answers presented here). It should be noted that this works in IE8, unlike most of the other methods (sadly I do need IE8 compatibility).
<script type="text/javascript">
window.onload = function() {
var detective = new Detector();
if (!detective.detect('Meat')){
var url = 'link/to/style.css'
if(document.createStyleSheet) {
try { document.createStyleSheet(url); } catch (e) { }
}
else {
var css;
css = document.createElement('link');
css.rel = 'stylesheet';
css.type = 'text/css';
css.media = "all";
css.href = url;
document.getElementsByTagName("head")[0].appendChild(css);
}
}
};
</script>
This detected that my browser wasn't accepting embedded fonts ("Meat" being one of the fonts I embedded) and served up the alternate CSS (although with a slight delay/flash of unstyled text, maybe because it's at the bottom of the page?) Anyhow, thanks again for all the help!