Preloading CSS still results in render blocking sources - javascript

Im trying to preload some CSS in the following way
Inside the Head Tag:
<link rel="preload" href="css/layout.css" as="style">
Script at the bottom of the Body Tag (Don't think it matters where its placed anyway...)
<script>
var rels = document.querySelectorAll( 'link[rel="preload"]' );
function loadCSS(){
for( var i = 0; i < rels.length; i++ ){
if( rels[i].as !== undefined && rels[i].as === 'style' ){
rels[i].rel = 'stylesheet';
continue;
}
//IE fix
if( rels[i].as === undefined && /(css)/i.test(rels[i].href)) rels[i].rel = 'stylesheet';
}
}
window.onload = function () {
loadCSS();
};
however, if i invoke the onload event in the following way:
<link rel="preload" href="css/layout.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
It's not Render-Blocking, however not supported in IE.
What am i missing?

//On window load
window.onload = function ()
{
//Get the link tag using the ID
var $style = document.getElementById('mycss');
//Now you can add, remove or change its attribute,
$style.rel='stylesheet';
//$style.href='';
};
<html>
<head>
<!-- Put a unique ID to your link tag -->
<link rel="preload" href="css/layout.css" as="style" id="mycss" />
</head>
<body>
</body>
</html>

Related

How to enable HTML import in other browsers using polymer?

As title, I used a HTML import link in my site:
<link rel="import" href="http://XX.XX.XX.XX/">
<script type="text/javascript">
var link = document.querySelector('link[rel="import"]');
var content = link.import;
// Grab DOM from warning.html's document.
var el = content.querySelector('body');
</script>
The variance "link" returns a document in Chrome, but returns null in Safari and other browsers. I know HTML import function is only supported by Chrome so far, so I added the following code before import link to load Polymer's webcomponents.js:
<script src="../webcomponentsjs/webcomponents-lite.js"></script>
but it still returns null in other browsers, can anybody tell me how to fix it?
It's because the <link> request is asynchonous.
Catch the HTMLImportsLoaded event, to parse the file only when it is loaded by the browser:
<script src="../webcomponentsjs/webcomponents-lite.js"></script>
<link rel="import" href="http://XX.XX.XX.XX/XX/warning.html">
<script type="text/javascript">
window.addEventListener( "HTMLImportsLoaded", function ()
{
var link = document.querySelector('link[rel="import"]');
var content = link.import;
// Grab DOM from warning.html's document.
var el = content.querySelector('body');
} )
</script>

How to load js/css files in custom popup load

In my project i am displaying a custom pop up page like below by javascript which has a form for user to fill,then I need to load some js files when pop up is loaded.
how to load js files,plz help.
<html>
<head>
<script type='text/javascript' src='files/jsfiles/core.js'></script>
</head>
<body>
<!- I need to call javascript function showUsers() from here->
<input type='button' onclick='showUsers();' value='listUsers'>
</body>
</html>
function loadScript(src) {
var script = document.createElement("script");
script.async = false;
script.src = src;
document.head.appendChild(script);
};
function loadStyle(src) {
var style = document.createElement("link");
style.rel = "stylesheet";
style.href = src;
document.head.appendChild(style);
};
function loadFiles() {
var scriptsArray = ['src1url', 'src2url'.., 'scrnurl'];
var csssArray = ['src1url', 'src2url'.., 'scrnurl'];
for (var i = 0; i < scriptsArray.length; i++) {
loadScript(scriptsArray[i]);
}
for (var i = 0; i < csssArray.length; i++) {
loadStyle(csssArray[i]);
}
};
function yoursubmitFcn(callback) {
// your functionality here;
callback();
}
$(document).ready(function () {
// do your stuff
yoursubmitFcn(loadFiles);
});
Also check: Another short form
You can use this library fancybox
Loading jQuery from CDN
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript" src="/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<link rel="stylesheet" href="/fancybox/jquery.fancybox-1.3.4.css" type="text/css"
media="screen" />
html
Sign in
JS
$('.open_pop').fancybox({
});
function openmsg_sent() {
jQuery(".open_pop").trigger("click");
}
For better and consistent UI, you can use a div which you can display with fixed positioning on click of the button.
I believe Alert wont be able to display css properties if am not wrong.
What you can do is, onclick of the button, in the JS, you can put your popup content into a div which is hidden initially and shown on click.
Hope this helps.

How to make button that removes div where it is located?

I want to make button that removes div where button is located.
This current solution removes current div only temporary, BUT i want it completely be removed from this html file. Is that possible?
I am done so far:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" media="screen" type="text/css" href="styles.css"/>
<title>Orders</title>
<center>
<style>
div
{width:797px;
border:2px solid;
background-color:white;
text-align:left;
margin-bottom:2px;}
</style>
<script type="text/javascript">
function deleteline(buttonObj)
{
var node = buttonObj;
do
{
node = node.parentNode;
}
while
(node.nodeType != 1 && node.nodeName != 'div');
node.parentNode.removeChild(node);
}
</script>
</head>
<center><a href=panel.html>back</a></center>
<div>
<input type="button" onclick="deleteline(this)" value="Remove this DIV" />
</div>
BUT i want it completely be removed from this html file.
The point is all you can do using JavaScript can actually creates client-side changes, so if you really want to delete the div element from your html file, the only thing you can do is creating a Server-side API and do a XHR request to that API, then remove it on the server side.
The other way to simulate this is to set an ID on that div element and save the last state of this element in the client using localStorage, after it got deleted, like:
function deleteline(buttonObj){
var node = buttonObj;
do {
node = node.parentNode;
}
while (node.nodeType != 1 && node.nodeName != 'div');
node.parentNode.removeChild(node);
var deleted_divs = localStorage["deleted_divs"];
var deletedDivs = deleted_divs ? JSON.parse(deleted_divs) ? [];
deletedDivs.push(node.id);
localStorage["deleted_divs"] = JSON.stringify(deletedDivs);
}
then check it whenever the DOM gets loaded:
document.addEventListener("DOMContentLoaded", function(event) {
var deleted_divs = localStorage["deleted_divs"];
if(deleted_divs){
var deletedDivs = JSON.parse(deleted_divs),
i = 0,
l = deletedDivs.length;
for( ; i < l ; i++){
var el = document.getElementById(deletedDivs[i]);
if( el ){
el.parentNode.removeChild(el);
}
}
}
});

CSS switcher - looking for more seamless implementation

I'm using a JS CSS switcher to good effect really brilliant. However, I would be delighted if it worked more seamlessly. At the point of opening a new page on the site the default css style often flickers on breifly, before the cookie re-applies the selected CSS style.
e.g. the canvas style is the default style, this opens when first visiting the site, user selects corporate style, they open another page in the site - the canvas style shows for a split second, then the corporate style loads over it. Worse on older computers, but on my main computer this does not often happen on Firefox, although on other browsers, especially Chrome its very noticeable. Does anyone have the expertise to update the workings below with a tweak to say, first check for the cookie, then if no cookie, apply the default style, rather than applying the default style seemingly at the same time?
the code I am using is here below:
in html head:
<script type="text/javascript">
$(function()
{
// Call stylesheet init so that all stylesheet changing functions
// will work.
$.stylesheetInit();
// This code loops through the stylesheets when you click the link with
// an ID of "toggler" below.
$('#toggler').bind(
'click',
function(e)
{
$.switcher();
return false;
}
);
// When one of the styleswitch links is clicked then switch the stylesheet to
// the one matching the value of that links rel attribute.
$('.styleswitch').bind(
'click',
function(e)
{
$.stylesheetSwitch(this.getAttribute('rel'));
return false;
}
);
}
);
</script>
<link rel="stylesheet" type="text/css" href="/css/canvas.css " title="canvas">
<link rel="alternate stylesheet" type="text/css" href="/css/corporate.css " title="corporate">
<link rel="alternate stylesheet" type="text/css" href="/css/earth.css " title="earth">
<link rel="alternate stylesheet" type="text/css" href="/css/space-and-stars.css " title="space-and-stars">
<link rel="alternate stylesheet" type="text/css" href="/css/under-the-sea.css " title="under-the-sea">
<link rel="alternate stylesheet" type="text/css" href="/css/classical.css " title="classical">
<link rel="alternate stylesheet" type="text/css" href="/css/creative.css " title="creative">
the JS
(function($)
{
// Local vars for toggle
var availableStylesheets = [];
var activeStylesheetIndex = 0;
// To loop through available stylesheets
$.switcher = function()
{
activeStylesheetIndex ++;
activeStylesheetIndex %= availableStylesheets.length;
$.stylesheetSwitch(availableStylesheets[activeStylesheetIndex]);
};
// To switch to a specific named stylesheet
$.stylesheetSwitch = function(styleName)
{
$('link[#rel*=style][title]').each(
function(i)
{
this.disabled = true;
if (this.getAttribute('title') == styleName) {
this.disabled = false;
activeStylesheetIndex = i;
}
}
);
createCookie('style', styleName, 365);
};
// To initialise the stylesheet with it's
$.stylesheetInit = function()
{
$('link[rel*=style][title]').each(
function(i)
{
availableStylesheets.push(this.getAttribute('title'));
}
);
var c = readCookie('style');
if (c) {
$.stylesheetSwitch(c);
}
};
}
)(jQuery);
// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
if (days)
{
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++)
{
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name)
{
createCookie(name,"",-1);
}
// /cookie functions
I would do it server-side...
Anyway, when you do
$(function()
{
});
jQuery waits until the DOM is fully load to execute the function.
So, you should place the javascript just below the <link />s section, outside $(function(){}); . This will make the script as soon as the browsers parses it, and before the page is fully loaded. (it has to be below the elements because they must be loaded)
I think you might wish to run your code before the DOM is ready. Perhaps you could run it immediately rather than using $(function(){...}), since jQuery waits until the page loads to execute anything in that (hence the flicker).
Also perhaps this might give insight.
http://forum.jquery.com/topic/use-jquery-before-the-dom-is-ready-12-1-2010
Debugging steps for why links are not working:
>>> $('link[#rel*=style][title]') --> seems to show your styles are there
[..., <link rel=​"alternate stylesheet" type=​"text/​css" href=​"/​css/​corporate.css " title=​"corporate">, ...]
>>> $.stylesheetSwitch('corporate') --> seems to work
The only problem is that the links are not having anything bound to the onclick; wait... don't you mean this.getAttribute('title')? as you can see above, rel="alternate stylesheet" which is probably not your intent to use as a unique theme identifier.

Use javascript to get the style of an element from an external css file

I have a html like this:
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="style.css">
</head>
<body>
<div id="test">Testing</div>
<script>
alert(document.getElementById('test').style.display);
</script>
</body>
</html>
The style.css:
div {
display:none;
}
I expect the js would return "none", but it return an empty string instead. Is there any way to solve this problem?
This would work for standards compliant browsers (not IE - currentStyle/runtimeStyle).
<body>
<div id="test">Testing</div>
<script type="text/javascript">
window.onload = function() {
alert(window.getComputedStyle(document.getElementById('test'),null).getPropertyValue('display'));
}
</script>
</body>
Since display is not set directly as a style property, you won't get that using the above code. You have to get the computed value.
You can refer this page, Get styles
To get the value
var displayValue = getStyle("test", "display");
function getStyle(el,styleProp)
{
var x = document.getElementById(el);
if (x.currentStyle)
var y = x.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
return y;
}
The CSS won't be loaded yet. Wrap your JavaScript in an "on-ready" event.
<body onload="alert(document.getElementById('test').style.display);">
Does that work for you?

Categories