Link to procedurally generated CSS as if it were an external file? - javascript

I'm using JavaScript to generate the text for a CSS file at runtime. I know that I can add this CSS to the HTML document by enclosing it in <style> tags, but it's a large file and my code would be less messy if it were to link to it as an external resource. Is it possible to link to a CSS file generated at runtime? There is no server involved and this must be done client-side.

Disclaimer: I will update this answer as the question is refined.
EDIT
It sounds like you are doing everything locally. In this case, it is not possible to write to your file system from scripts (like JavaScript) running in the browser (largely enforced for security reasons). While you can link and load CSS files from your local machine, you cannot write to them.
OLD ANSWER
You have a couple options, but I am most interested in what environment you are working in. The assumptions are in bold.
JSON color file stored on server: You should be generating this stylesheet on the server-side, and serving it up to your client. This involves creating a route (URL) to access the dynamically generated stylesheet, outputting formatted CSS (not too hard), and setting the headers with the correct MIME types. How you do the last part varies based on your server implementation (Node.js vs. PHP vs. etc.)
Can generate stylesheet only on client side (no server): In this case, assuming you do not have access to a server, but you can fetch your JSON color file (from somewhere, I guess), you really have no stylesheet resource to link to. This really limits optimization potential in terms of cacheing, etc.
Your only real option here is to create and populate the stylesheet in the browser. There is a decent article on how to do that here: Add Rules to Stylesheets with JavaScript

Have you tried this-
loadCssFile = function(fileName) {
var cssLink = $("<link rel='stylesheet' type='text/css' href='"+fileName+"'>");
$("head").append(cssLink);
};
// load the css file
loadCssFile("style.css");

Related

Is it possible to alter actual css file using javascript?

I want to modify the CSS file using data that I get from the database. So, after the login, I am getting all the necessary data from DB and update styleSheet using insertRule/deleteRule methods then, redirect to the main page.
Login -> Theme engine page (modify css) -> home page
Theme engine page (theme.html) is an empty HTML page with one JS file (themeEngine.js) which modifies CSS file.
I checked the stylesheet in theme.html it is same as the expected result but, when it redirects to home page the CSS file goes back to its default version. The methods insertRule/deleteRule is not altering an actual file!
I tried importing themeEngine.js to every existing HTML file but in that case, default style appears (for a little amount of time, depending on the internet speed) before the theme engine starts to work and importing js file to every page is quite inconvenient.
I would like to know how can I solve this problem: having a custom style for every user. Is it possible to edit an actual CSS file using JavaScript?
Browsers can't change data on a server without explicit support from it by the server. (Imagine how long the Google homepage would survive otherwise!)
Typically you would need to pick a server-side programming language, use it to write an API, and then interact with it using Ajax.

How to link javascript in html

I am creating browser based video editing tool. I want a user to first download a ~70mb javascript file and store it somewhere on his computer. I want to link that file when my website is opened. How can I achieve that.
EDIT
What i meant is that there are various files like js1.js,js2.js... all sums upto 70mb . So i will offer a zip folder to download and only link js1 or js2 file etc depending on the effects user wish to apply
i am sorry to inform you but i think there is something really wrong with what you are trying to do.
A "solution" would be to just cache the javascript on the user's browser so any subsequent requests parse the cache instead of requesting the resource again from the server.
You should know however that if you are in need to download ~70mb of a javascript file you are doing something wrong. I have a whole web app project that when published the total size is around 60mb, all files required to properly run included, and its a damn big codebase in there.
I find it very hard to believe there is ever a need for a single javascript file to be that big, in any case maybe a simple caching should do the trick
That is actually done automatically. Once you add a <script> tag with a link to a local js file (also stored on the server) the file is loaded automatically.
See HTML <script> src Attribute for more information on that.
You can only reference to js files on the server. Files on the server could look like this:
index.html
somefancyjsfile.js
You can then reference from inside your html file to the js file via the <script> tag.
I'm not sure though if the size is not a bit too much...

collect all the js css and img resources used in a html file

I want to write a npm package to localize an html url.
1. using the html url download the html page
2. parse the html file, extract all the js, css and img files used in the html and local these resources.
3. If these js, css and img files using some external resources, localize these resources. For example, extract background image in the css.
The first and second requirements are easy to meet. But I have no idea about the last one.
I can parse the all the css files and localize the resources used in it. But how can I parse the js files?
For example:
If the js adds a 'script src = XXX' tag into the html dom, how can I extract the src?
I think I would try to use a headless browser to catch every network calls instead of trying to parse the code.
I didn't used it personally but PhantomJS seems to fit the bill.
It can be used to load a webpage then execute any script / css that would normally happen on the request and execute stuff once the page is loaded.
The network monitoring features are probably what you'll want to use.

Siteminder Fcc attribute not read in seperate javascript file

I have a login.fcc page which I want to modularize into Javascript,CSS & HTML modules so that it can be maintained easily.
As you know in Siteminder FCC pages we have number of Attributes which we can access and write code accordingly.
When I try to pull this $$smauthreason$$ in seperate js file I am not able to access the attribute value.(this value shd be set by siteminder when this fcc page is called).
Any ideas why I am not able to put this javascript code in seperate js file?
SiteMinder web agent will only serve .fcc files. If you have another file (.js) you must host it on another server instance, but you will not be able to access the SM attributes from it.
As stated before, the FCC file is the only file processed by the web agent,so you can't do the variable substitution in other files.
I think probably what i'd suggest is binding all the variables to 'global' javascript variables in your fcc file. This would allow you to import javascript source files into the HTML that would have access to the variables, but as javascript variables and not $$USER$$,etc type variables.
The other thing you might play with (and I have not done this) is to try server side includes if you're using apache. If the server side includes are processed BEFORE the fcc handler, then you might be able to modularize more.

Javascript read files in folder

I have the following problem which I'm trying to solve with javascript. I have a div with a background image specified in a css file, and I want my javascript to change that image periodically (let`s say every 5 secs).
I know how to do that, the problem is that I have a folder of images to choose from for the back image. I need to be able to read the filenames (from the image folder) into an array, change the background image of the div, delay for 5 seconds and change again.
in your javascript, use an array like
var images = [ "image1.jpg", "image2.jpg", "image3.jpg" ];
function changeImage() {
var image = document.getElementById("yourimage");
image.src=$images[changeImage.imageNumber];
changeImage.imageNumber = ++changeImage.imageNumber % images.length;
}
changeImage.imageNumber=0;
setInterval(changeImage,5000);
The values in the array should be generated by your php
You're still going to need php or asp to query the folder for files. Javascript will not be able to "remotely" inspect the file system.
You can do something like the following in jQuery:
$.ajax({
url: 'getFolderAsArrayOfNames.php',
dataType: 'json',
success: function(data) {
for(var i=0;i<data.length;i++) {
// do what you need to do
}
});
});
And in your getFolderAsArrayOfNames.php, something like this:
echo "function "
.$_GET['callback']
."() {return "
.json_encode(scandir('somepath/*.jpg'))
."}";
If you are using Apache as your
web server, and
if you can configure
it to provide a default directory
listing for your images folder (use
the appropriate options in
httpd.conf and/or .htaccess), and
if you don't care that the list of
images is available to everyone who
visits your web site,
then you don't need PHP or any other server-side processing.
You can use XMLHttpRequest (or the jQuery ajax function, which is a nice wrapper) to get the listing for the folder. The response will be HTML and it will look something like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>Index of /demo1/images</title>
</head>
<body>
<h1>Index of /demo1/images</h1>
<pre><img src="/icons/blank.gif" alt="Icon "> Name Last modified Size Description<hr><img src="/icons/back.gif" alt="[DIR]"> Parent Directory -
<img src="/icons/image2.gif" alt="[IMG]"> tree.gif 17-Mar-2009 12:58 6.2K
<img src="/icons/image2.gif" alt="[IMG]"> house.gif 17-Mar-2009 12:58 6.5K
<img src="/icons/image2.gif" alt="[IMG]"> car.gif 02-Mar-2009 15:37 8.4K
<img src="/icons/image2.gif" alt="[IMG]"> elephant.jpg 02-Mar-2009 15:37 3.4K
<hr></pre>
<address>Apache/2.0.63 (Unix) Server at zeppo Port 80</address>
</body></html>
Since this output is pretty predictable, you might try parsing out the filenames using a JavaScript regular expression, but it's probably just as easy and more robust to create a hidden DIV on your page, put the HTML response into that DIV, and then use DOM methods to find <a href>s that are after <img> tags with an alt="[IMG]" attribute. Once again, using jQuery Selectors or similar helper methods available in other toolkits will make this DOM parsing pretty easy.
Once you have the URL of the new image (parsed from the href), you can set the new CSS background for your div with the .style.backgroundImage property.
You cannot do any file IO using JavaScript mainly because of security reason, so anyway you have to create some back end service which will update you with an list of available files in your folder. You don't have to do it in a hard way, you can use AJAX to it smoothly and nicely
You can't read a folder's contents, neither on the server nor on the clientside.
What you can do is to read the folder's contents with the help of a serverside script, and load it to a JavaScript array while processing the page.
This would not be ideal but in the absence of server-side processing (which you really should be doing--either PHP or Rails or Perl or whatever your host supports), you could allow directory listing on your images folder. This has security implications.
Then loading e.g., http://mysite.com/rotatingImages should respond with a list of files. You could do this with AJAX, parse out the relevant hrefs, push them onto an array and render your rotating images in JS.
You must send the list of names along with the JavaScript and then iterate through it.
A noted above, you can not access server's system from a client's browser (which is where JavaScript runs).
You have 3 possible solutions:
Create the JavaScript file via some dynamic back-end (php or perl scripts are best for that).
The main JavaScript function could still be static but the initialization of the array used by it (either as a snippet on the main HTML page or a separate .js imported file) would be a php/perl generated URL.
A recent StackOverflow discussion of the topic is at link text
Make an XMLHttpRequest (AJAX) call from your JavaScript to a separate service (basically a URL backed by - again - php/perl backend script) returning XML/JSON/your_data_format_of_choice list of files.
This is probably a better solution if you expect/want/need to refresh a frequently-changing list of images, whereas a pre-built list of files in solution #1 is better suited when you don't care about list of files changing while the web page is loaded into the browser.
An un-orthodox solution - if browsers you care about support animated background images (gif/png), just compile your set of images, especially if they are small sized, into an animated gif/png and use that as background.

Categories

Resources