Inject css to page without using onload (IE)? - javascript

I've written a widget which relies on having to inject a css file onto the html page.
I am using the following code to inject the css-sheet:
var link = document.createElement("link");
link.href = "http://myurl.com/style.css";
link.rel = "stylesheet";
document.body.appendChild(link);
This works in all browsers except for IE, for this to work in IE i have to do a:
window.onload
Like this:
window.onload=function() {
//inject here
}
I want to find a way to accomplish this without having to use window.onload, since window.onload only loads my widget when all of the pages has loaded, for bigger pages it takes forever to load the widget.. Is there any workaround for this?

I am assuming the this script is in the body. Append it to the head and not the body
document.getElementsByTagName("head")[0].appendChild(link);

Related

Reload iFrame (same-domain) without changing `src=`

I am dynamically creating iframe , which just contains content (no src attribute).
var iframe = document.createElement('iframe');
iframe.contentWindow.document.body.innerHTML= my_page_content;
....
however, JS scripts (<script src="....." inside my_page_content) are not being loaded and I have to re-load scripts.
these methods wont help me to reload frame:
//this one emptyfies the iframe at all
iframeElement.src = iframeElement.src
//this one is not possible, because the `<script>` links are embedded in the content already.
var script = doc.createElement('script'); script.src = "jquery.min.js";
framebody.appendChild(script);
what are the solutions to force the iframe to load the included scripts in its html content? maybe I am attaching the content in a wrong way?
The only way I've solved this was to write the body inside iframe using write() command:
var ifr = iframeElement.contentWindow.document;
ifr.open(); ifr.write("<body>"+ my_page_content +"</body>"); ifr.close();
neither appendChild() nor .innerHTML helped me.

how to add dynamically css to head after click on a href link

Is it possible to import css stylesheets to test.php head after redirect page to test.php after click on a href link from index page using Javascript? If so, how can it be done?
problem is that styles.css not working or display in test.php page?
i have code like this:
Index Page
<a id="some_id" class="optional_has_click">Click Me</a>
Jquery
<script type="text/javascript">
$(document).ready(function(){
$("#some_id").click(function(){
// add dynamically css file from external link and display to head
window.location.href = 'test.php';
var cssId = 'styles';
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://example.com/styles.css';
link.media = 'all';
head.appendChild(link);
document.write("<style>#jstree-marker-line,
#preloader{ background:none !important}</style>");
});
});
</script>
test page
<div id="container">
<p>test</p>
</div>
You cannot use document.write after the page has loaded, but if you really want to add styles like this to the head of the page you could potentially try something like this:
$("head").append("<style>...</style>");
But, it's probably better to do something like this when you want to update a style on the page
$("#jstree-marker-line").css("background", "none");
Or you could have a class with the styles you need defined on the page and use jquery's addClass to add that class dynamically on click
Using window.location.href = 'test.php'; will load a different page and stop any JavaScript running after that point.
Check out this question: How can I make JavaScript make (produce) new page? as it may answer your problem, or run the rest of the script on the test page.
Also check out #JenGettings' answer instead of document.write as it will overwrite the page.

Adding a stylesheet dynamically

After the document.ready event fires, I load the stylesheet dynamically based on the user's resolution. This is what works in Chrome, Firefox and IE:
var TheFileName = '/SomeDirectory/SomeFileName.css';
if (document.createStyleSheet) {
//finally found something IE got right
document.createStyleSheet(TheFileName);
} else {
$('<style id="TestCSS" type="text/css"></style>').appendTo('head');
$.get(TheFileName , function (TheCSS) {
$("#TestCSS").append(TheCSS);
});
}
The problem is that it doesn't work in Safari. I don't have a mac so I don't have the console error but all I know is that the stylesheet doesn't get added. What do I need to change to make it work in Safari?
PS: I don't want to use media queries.
Edit
I initially had a function that used a <link> tag that was added. My page is entirely dynamically generated and the problem is that adding the stylesheet after the DOM is rendered makes the elements unstyled if you use a <link> tag. So what I do is use a setTimeout to check for $('#TestCSS').length to see if the stylesheet loaded and then I fire the functions that create the HTML. With a tag, there's no way of knowing when the CSS is attached.
Why not just insert the stylesheet as a link tag, instead of loading it with ajax, should be cross-browser ?
var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.type = 'text/css';
link.href = '/SomeDirectory/SomeFileName.css';
document.head.appendChild(link);

load css file using javascript

I'm new to javascript.
I'm trying to load a .css file using the following javascript code, but it seems not working.
var myCss = document.createElement("link");
myCss.type = "text/css";
myCss.rel = "stylesheet";
myCss.href = "mycss.css";
document.getElementsByTagName("head")[0].appendChild(myCss);
Can anyone help?
thanks.
You have in stackoverflow another question about it, you can find it here:
How to load up CSS files using Javascript?
Which is a "oldschool" way to do it, just like user58777 said. (Credits go to him)
His code:
var $ = document; // shortcut
var cssId = 'myCss'; // you could encode the css path itself to generate id..
if (!$.getElementById(cssId))
{
var head = $.getElementsByTagName('head')[0];
var link = $.createElement('link');
link.id = cssId;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://website.com/css/stylesheet.css';
link.media = 'all';
head.appendChild(link);
}
Why are you trying to do this? What benefit are you expecting?
I've never come across a situation where this is a good idea. CSS files are usually pretty small, so you aren't really gaining much by loading them dynamically. Just do the load in the head tag.
Anyway, the code you have should work. Just be sure that path is correct (it will be relative to the html file you're running)
Another solution would be to load an html file with all of the markup you need, and append it to the body. Check out the jQuery.load function The line below will load gameMarkup.html into the body tag.
$( "body" ).load( "gameMarkup.html" );
You can include all of the markup for your game here (not just styles). Generating elements with js can be useful, but it makes the code harder to maintain.
If you aren't using jquery, you can do the same thing with XHR, but it will be a lot more lines of code.

My Javascript is supposed to load one CSS on click, but loads both at the same time

When I launch my page, the css is totally messed up because my js is supposed to dynamically load css on click (mobile or standard website css). Currently, it just loads them both. Here's the code:
function loadjscssfile(filename, filetype)
{
if (filetype=="css")
{
var fileref = document.createElement("link");
fileref.rel= "stylesheet";
fileref.type = "text/css";
fileref.href = filename;
document.getElementsByTagName("head")[0].appendChild(fileref)
}
}
loadjscssfile("HCSS.css", "css")
I have two links on the site. One loads the mobile css, the other loads the standard website css. I have it linked like this:
load hcss
<br/>
load mobile
What you are after is swapping css files, not just loading a new one. In jquery it would probabaly look something like this (code not tested):
function swapCssFiles(fileToLoad, fileToUnload) {
$('head link[href="'+fileToUnload'"]') // select the tag with css to unload
.attr('href', fileToLoad); // swap the href attribute with the file to load
}
This is off course possible with 'pure' javascript, but I'm to much a jQuery addict to tell you how. If you see how easy the syntax is, you can probably tell why.
Your links would look something like this:
load hcss
I hope this is helpfull.
Note however that this is not the way I would approach this. If you want to target mobile devices with specific css, I would use mediaqueries to detect screensize, and not javascript.

Categories

Resources