Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 11 of 11
  1. #1
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts

    CSS, HTML, and XML in a .js file

    intro


    ".js" files typically house JavaScript code for roll-overs, image pre-loaders, pop-up window formatting etc...

    The text inside of ".js" files must be valid JavaScript and must also follow a few other rules:
    • No <script> tags inside
    • All Non-ASCII characters must be escaped. ex: ( tab becomes "\t" )
    • Quotes inside of strings must be encoded. ex: ( "Dan's" becomes "Dan\'s")
    • Invalid code must halt the loading of the script file.
    • Multi-line strings must be broken up by line and/or encoded.



    Important fact: Unlike web (.htm), rss (.xml), or any other text-based format,
    JavaScript files (".js") can be accessed and used from one web site to the next,
    regardless of the domain where the file is stored.



    This 'unlocked' aspect of javascript has some great potential.
    This leads to increasing interest in JSON, a way to store more than just roll-over code in JavaScript.

    Data stored as JSON is valid javascript code, and can thus come from anywhere.
    Unfortunatly, the 'unlocked' potential is hampered by the strict rules noted above.
    JSON data must be carefully encoded and managed so as to follow the rules.
    A single invalid character can destroy (invalidate) an entire data structure, rendering the data unavailable.


    Side-Note:You can remotely fetch JSON data, run JavaScript files, use CSS style-sheets, and display images from anywhere.
    _______________________________________________

    Programming Frustration:

    There is no simple and efficient way to include common data formats like html, csv, xml, and css into JavaScript files.

    This prevents some potentially-useful possibilities:
    • storing human-readable HTML snippets
    • storing CSS stylesheets for different browsers in one file
    • storing long, multi-line text blocks in a wysiwyg fashion
    • serving RSS data across domains
    • placing all the needed scripts, html, and css for a page into a single file



    Say i want to store: (250 bytes)
    Code:
    <tt>
    <b>Sunday, September 9'th at 8pm, "evening's start"</b>
    Temperature: 74°F
    Dewpoint: 	  62°F
    Heat Index: N/A
    Surface Wind:  N 6mph
    Sky Cover: 	  38%
    Precipitation Potential: 14% 
    Relative Humidity: 66%
    Thunder:    <10%
    Rain: 		<10%
    </tt>
    to pack that into a script file one could encode the data.
    Code:
    window.escape:(413 bytes) %3Ctt%3E%3Cb%3E%22Sunday%2C%20September%209%27th%20at%208pm%2C%20%22evening%27s%20start%22%20%22%3C/b%3E%0ATemperature%3A%20%0974%B0F%0ADewpoint%3A%20%09%20%20%2062%B0F%0AHeat%20Index%3A%20%09%20N/A%0ASurface%20Wind%3A%20%20N%206mph%0ASky%20Cover%3A%20%09%20%2038%25%0APrecipitation%20Potential%3A%2014%25%20%0ARelative%20Humidity%3A%2066%25%0AThunder%3A%20%20%20%20%3C10%25%0ARain%3A%20%09%09%3C10%25%0A%3C/tt%3E 
    
    
    base64: (332 bytes)PHR0PjxiPiJTdW5kYXksIFNlcHRlbWJlciA5J3RoIGF0IDhwbSwgImV2ZW5pbmcncyBzdGFydCIgIjwvYj4KVGVtcGVyYXR1cmU6IAk3NLBGCkRld3BvaW50OiAJICAgNjKwRgpIZWF0IEluZGV4OiAJIE4vQQpTdXJmYWNlIFdpbmQ6ICBOIDZtcGgKU2t5IENvdmVyOiAJICAzOCUKUHJlY2lwaXRhdGlvbiBQb3RlbnRpYWw6IDE0JSAKUmVsYXRpdmUgSHVtaWRpdHk6IDY2JQpUaHVuZGVyOiAgICA8MTAlClJhaW46IAkJPDEwJQo8L3R0Pg
    
    JavaScript escaping: (252 bytes)<tt><b>\"Sunday, September 9\'th at 8pm, \"evening\'s start\" \"<\/b>Temperature: \	74°FDewpoint: \	   62°FHeat Index: \	 N\/ASurface Wind:  N 6mphSky Cover: \	  38%Precipitation Potential: 14% Relative Humidity: 66%Thunder:    <10%Rain: \	\	<10%<\/tt>
    
    Or my personal favorite: many strings. (310 bytes)
    b="<tt><b>\"Sunday, September 9\'th at 8pm, \"evening\'s start\" \"</b>"
    b+="Temperature: \	74°F"
    b+="Dewpoint: \	   62°F"
    b+="Heat Index: \	 N/A"
    b+="Surface Wind:  N 6mph"
    b+="Sky Cover: \	  38%"
    b+="Precipitation Potential: 14% "
    b+="Relative Humidity: 66%"
    b+="Thunder:    <10%"
    b+="Rain: \	\	<10%"
    b+="</tt>"
    Each method has severe downsides though:
    they take up a lot of extra space, are humanly unreadable, and difficult to edit once encoded. They also require additional processing overhead.

    Many tutorials will tell you that there is no way around encoding.


    I have developed a technique to place almost any text inside of a .js file, without any encoding or other processing, and retrieve it verbatim to a string variable.

    I must mention a limitation to this technique:
    It only works in IE and Firefox.

    those two browsers cover the over-wealming majority (95%) of surfers in fairness.

    So what is the solution already?

    How it works:
    1. You wrap a little bit of text around the data you want to include.
    2. You paste the block into your script file.
    3. Your data is available as a string or a function result.

    The magic code:
    Code:
    //by dandavis
    
    var weather= (function(){//@cc_on; /*  
    this.info=<i><![CDATA[
     
     
    <tt><b>"Sunday, September 9'th at 8pm, "evening's start" "</b>
    Temperature: 	74°F
    Dewpoint: 	   62°F
    Heat Index: 	 N/A
    Surface Wind:  N 6mph
    Sky Cover: 	  38%
    Precipitation Potential: 14% 
    Relative Humidity: 66%
    Thunder:    <10%
    Rain: 		<10%
    </tt>
    
    ]]></i>// /*  */
    
    if(!! this.info){var ww=this.info.toString()}else{ww=arguments.callee.toString().split(/\[CDATA\[/m)[1].toString().split(/\]\]\>/im)[0]};
    return ww;}() )
    
     
    //end example of anon function form



    Technical Information:
    This technique uses 2 different, proprietary aspects of IE and Firefox.

    IE returns text contained inside of comments (/* */) within functions when calling the function's .toString() method.

    FireFox supports a unique type of data: XML.
    XML strings can be defined without escaping.
    XML can store arbitrary data inside of CDATA sections.

    By combining these qualities into a single function,
    I was able to get broad-based browser coverage in a one-stop solution.

    The XML data type is a standard, so it is conceivable that safari and opera will support it in the future; let's hope so!


    Limitations:
    Ok, so nothing is perfect, and a couple things can trip-up the process.
    The text you pack in must respect the following minor limitations:
    1. The text cannot contain any CSS comments
    2. The text cannot contain any multi-line type ( /* */ ) JavaScript comments. ( '//' ok)
    3. The text cannot contain any XML CDATA sections
    4. The text cannot contain broken/partial/invalid HTML comment sections ( <!-- --> )

    Thats it, everything else works.

    To assist in utilizing the system, i offer some helpful code:
    Code:
    
    
    //LIBRARY CODE - for examples and authoring tools
    function obValsl(ob) {
        var r = [], i = 0, mx = ob.length;
        for (var z = 0; z < mx; z++) {
            r[z] = ob[z];
        }
        return r;
    }
    
    function tags(tid) {
        return obValsl(document.getElementsByTagName(tid));
    }
    
    function el(tid) {
        return document.getElementById(tid);
    }
    
    
    function aCSS(iCSS) {
        var vi = "adds a css tyle section to the document, filled with text like an external stylesheet";
        var D = document;
        var h = D.getElementsByTagName("head");
        if (!h.length) {
            return;
        }
        var ns = D.createElement("style");
        ns.type = "text/css";
        h[0].appendChild(ns);
        try {
            ns.styleSheet.cssText = iCSS;
        } catch (e) {
            try {
                ns.appendChild(D.createTextNode(iCSS));
                ns.innerHTML = iCSS;
            } catch (e) {
            }
        }
    }
    
    function CB() //sets or read clipboard in IE accepts 1 arg to set, returns cb when arg1 is null
    {if (arguments.length)     {window.clipboardData.setData('Text', arguments[0])}
    else 	{ return window.clipboardData.getData('Text')}
     }//end CB
    
    function dataUrlStr(data) {
        return "data:text/plain," + escape(data);
    }
    
    
    
    String.prototype.stripComments=function () {
        return this.replace(/\/\*.+\*\//gm, "");}
    
    String.prototype.packIn=function () {
        return "(function(){//@cc_on; /*  \nthis.info=<i><![CDATA[" + this.stripComments() + "]]></i>// /*  */\n\nif(!! this.info){var ww=this.info.toString()}else{ww=arguments.callee.toString().split(/\\[CDATA\\[/m)[1].toString().split(/\\]\\]\\>/im)[0]};\nreturn ww;}() )";
    }
    
    
    Usage: adds a .packIn() method to all strings in javascript.
    "any string".packIn() returns a new string.
    The returned string is the JavaScript code to be pasted into your .js file.

    of course, you can D-I-Y by putting
    Code:
    (function(){//@cc_on; /*  
    this.info=<i><![CDATA[
    before your text block, and
    Code:
    ]]></i>// /*  */
    
    if(!! this.info){var ww=this.info.toString()}else{ww=arguments.callee.toString().split(/\[CDATA\[/m)[1].toString().split(/\]\]\>/im)[0]};
    return ww;}() )
    after the block.




    here are a few snippets to help:
    bookmark the link below (Firefox only), click it while selecting text on any page, and it will give you a textbox containing packed version.

    selection to .js


    In IE, this snippet packs any text on clipboard, and pastes the result back onto the clipboard:
    Code:
    CB(CB().packIn())

    Practical Examples:


    store a simple string in a pre-defined var:

    Code:
    var myVar=(function(){//@cc_on; /*  
    this.info=<i><![CDATA[
    Hello World!
    ]]></i>// /*  */
    
    if(!! this.info){var ww=this.info.toString()}else{ww=arguments.callee.toString().split(/\[CDATA\[/m)[1].toString().split(/\]\]\>/im)[0]};
    return ww;}() )
    
    alert(myVar);


    add a CSS style sheet from inside a .js file
    Code:
    aCSS(function(){//@cc_on; /*  
    this.info=<i><![CDATA[
    
    .yellow  {
    	font-family : Arial, Helvetica, San Serif;
    	font-size : 9pt;
    	font-weight : bold;
    	color : #F0E68C;
    }
    
    .searchinput, .searchinput SELECT, .searchinput INPUT  {
    	font-size : 8pt;
    }
    
    td  {
    	font-size : 9pt;
    	font-family : Arial, Helvetica, San Serif;
    }
    
    th  {
    	font-family : Arial, Helvetica, San Serif;
    	font-size : 8pt;
    	font-weight : normal;
    }
    
    ]]></i>// /*  */
    
    if(!! this.info){var ww=this.info.toString()}else{ww=arguments.callee.toString().split(/\[CDATA\[/m)[1].toString().split(/\]\]\>/im)[0]};
    return ww;}() )

    inject a table into the document
    Code:
    //assumes an empty div with the id "footerDrop" is somewhere in the document.
    
    el("footerDrop").innerHTML=(function(){//@cc_on; /*  
    this.info=<i><![CDATA[
    
    <table align="center" width="650">
    <tbody><tr valign="top">
    	<td class="gray" align="left">
    	<a href="http://www.crh.noaa.gov/ilx">NOAA's National Weather Service<br>Lincoln, IL</a>
    	</td>
    	<td class="gray" align="left">
    	<a href="http://weather.gov/disclaimer.php">Disclaimer</a><br>
    	<a href="http://weather.gov/credits.php">Credits</a><br>
    
    	<a href="http://weather.gov/glossary/">Glossary</a>
    	</td>
    	<td class="gray" align="left">
    	<a href="http://weather.gov/privacy.php">Privacy Policy</a><br>
    	<a href="http://weather.gov/admin.php">About Us</a><br>
    	<a href="http://weather.gov/careers.php">Career Opportunities</a>
    	</td>
    
    </tr>
    </tbody></table>
    
    ]]></i>// /*  */
    
    if(!! this.info){var ww=this.info.toString()}else{ww=arguments.callee.toString().split(/\[CDATA\[/m)[1].toString().split(/\]\]\>/im)[0]};
    return ww;}() )





    store an entire webpage in a string, write during load.
    Code:
    document.write((function(){//@cc_on; /*  
    this.info=<i><![CDATA[
    
    
    <html>
    <head><title>Transit Computer</title></head>
    <body>
    <h4>U.S. Naval Observatory<br>Astronomical Applications Department</h4>
    <pre>
                            Transit of Venus of 2012 June 06                        
                                     Delta T:  68.2s                                
         
                            WASHINGTON, DISTRICT OF COLUMBIA                        
                     Location:  W 77°01'48.0", N38°53'24.0",     0m                 
                       (Longitude referred to Greenwich meridian)                   
         
                                                    Sun's          Position   Angular
                                   UT1       Altitude   Azimuth     Angle    Separation
                                h  m   s         °          °          °          '
    Transit Begins             22:03:57.9      25.9      279.2       41.2       16.2
    Ingress Interior Contact   22:21:29.0      22.5      281.6       38.7       15.3
    Sunset                     00:30           ----      300.5      -----       ----
         
                     Duration:    2h 26m 28.0s
           Solar Semidiameter:   15' 45.7"
        Semidiameter of Venus:    0' 28.9"
    
    </pre>
    </body>
    </html>
    ]]></i>// /*  */
    
    if(!! this.info){var ww=this.info.toString()}else{ww=arguments.callee.toString().split(/\[CDATA\[/m)[1].toString().split(/\]\]\>/im)[0]};
    return ww;}() ))





    Further Consideration
    ____________
    1. a javascript file doesn't have to be named .js, it can end with anything.
    2. .htm files will execute in browsers.
    3. one file can be both. hint: //<html><script src="mypage.htm"> ...
    ____________
    the function will always return a string, and the content is never evaluated.
    tailor a specific package by modifying the last part, "return ww;".
    ____________
    you can use the package anywhere you would normaly use a string
    -in an array, as a function argument, in the middle of a JSON object, etc.
    ____________
    packIn the big, repetitive sections of your webpage, and serve them from a free server or ip address to lower bandwidth costs incurred on your homepage server.
    ____________
    buddies can share packIn'd blog entries from many web sites - add a <script> tag pointing to each file to subscribe. build a stack (array of strings) as the blogs arrive.
    onLoad, turn the array into html and set .innerHTML of document.body with the joined result.
    ____________
    put rich html documentation in your script file. as noted, script files saved with a .htm extension can be viewed right in the browser.
    ____________
    if you don't need to cross domains, a safari/opera fallback could ajaxly GET file-based backups.
    ____________




    this is step two of three in my work at reducing domain restrictions.
    step one was set of json encoders
    step two uses wraps, not encoding
    step three unlocks plain files w/o even wrapping. now in debugging.



    if there is interest (indicated by replies, private messages, thanks, etc) i can post more demos.


    if anyone gets it to work in opera or safari, i would love a copy.



    last thing: some of the javascript code included in this post is part of a larger, soon to be released, library.
    Upon release, this library is expected to require a license for commercial use.
    feel free to contact me for more info.

    -Enjoy

    Last edited by rnd me; 09-09-2007 at 05:44 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #2
    Regular Coder
    Join Date
    Aug 2002
    Location
    Silicon Valley, CA
    Posts
    980
    Thanks
    0
    Thanked 0 Times in 0 Posts
    The first and most obvious question I need to ask is, why are you trying to misuse an existing file type for this? .js is for JavaScript. If you want CSS, you use .css.

    I appreciate the kind of flexibility you're trying to provide with this solution, but I seriously have to question whether this is the right way to accomplish that... and I can't, in good conscience, recommend a method that does away with best practices for a method that functions in complete absence of a semantically-valid mindset.

    Why wouldn't you use server-side loading of content, or even XMLHTTPRequest for this? Both are better suited for this particular task. You can load HTML, CSS, JavaScript, XML, or any other type of content using XMLHTTPRequest and apply it to your document without the need for mixing media types together like this.

    Sorry to sound so negative after you've obviously put a lot of work into this, but this is like trying to heal a wound with lemon juice. It's the wrong tool for the job.

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    Quote Originally Posted by Skyzyx View Post
    The first and most obvious question I need to ask is, why are you trying to misuse an existing file type for this? .js is for JavaScript. If you want CSS, you use .css.

    I appreciate the kind of flexibility you're trying to provide with this solution, but I seriously have to question whether this is the right way to accomplish that... and I can't, in good conscience, recommend a method that does away with best practices for a method that functions in complete absence of a semantically-valid mindset.

    Why wouldn't you use server-side loading of content, or even XMLHTTPRequest for this? Both are better suited for this particular task. You can load HTML, CSS, JavaScript, XML, or any other type of content using XMLHTTPRequest and apply it to your document without the need for mixing media types together like this.

    Sorry to sound so negative after you've obviously put a lot of work into this, but this is like trying to heal a wound with lemon juice. It's the wrong tool for the job.
    i made this drawing from my experiences with ajax.
    this is certainly to be considered an alternate transport.
    the origional need was to put unparsed raw text right into code, without having to tediously escape it. this is good for documentation and templating.


    i would recommend always using the best method available.

    but there are times when xmlHTTRequests cannot be used.
    this is something you can use in places where existing solutions fall short.


    for example:
    writing applications that don't use server-side code, relying upon javascript to build the user interface.

    writing applications that access data from several domains. unlike a (.htm) webpage, javascript can load a wrapped html page from anywhere. this would let you store your heavy data somewhere on a simple storage plan, and host your app from a server package.


    templating. unlike precarious document.createElement, appendChild, etc ad nauseum, you can drop real html snippits into a javascript variable. you are then a .replace or two away from the finished product.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #4
    Senior Coder rangana's Avatar
    Join Date
    Feb 2008
    Location
    Cebu City, Philippines
    Posts
    1,752
    Thanks
    65
    Thanked 372 Times in 365 Posts
    "selection to .js" link failed.
    Learn how to javascript at 02geek

    The more you learn, the more you'll realize there's much more to learn
    Ray.ph

  • #5
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    Quote Originally Posted by rangana View Post
    "selection to .js" link failed.
    egads censored again.

    edit the broken bookmark's properties, change location to :
    Code:
    javascript: String.prototype.stripComments = function () {return this.replace(/\/\*.+\*\//gm, '');};String.prototype.packIn = function () {return '(function(){//@cc_on; /*\nthis.info=<i><![CDATA[' + this.stripComments() + ']]></i>// /**/\n\nif(!! this.info){var ww=this.info.toString()}else{ww=arguments.callee.toString().split(/\\[CDATA\\[/m)[1].toString().split(/\\]\\]\\>/im)[0]}; return ww;}() )';};document.write('<textarea rows=33 cols=90>' + document.getSelection().toString().packIn());document.close();
    it puts an expression that returns the selection into the textbox.

    for some reason, it adds </html> to the the end of the textbox, but you can copy around it...
    Last edited by rnd me; 06-12-2008 at 04:56 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #6
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts

    update: 2013

    it's been a while since i posted this and recent browser developments have lead to a much simpler version of this capability being widely deploy-able.

    Five years is a long time on the web, huh?

    Now, a comment transport system works in everything except very early versions of opera that don't support Function.toString(). Even IE6 should be able to handle this system.

    I find it useful for building widget modules that use a little CSS to define layout. Instead of having two files to manage in two places (.css + .js), i can put the css inside the js, and yet still edit it naturally in my text editor. I've also created some rich inline documentation complete with hyperlinks, that is later robotic-ally parseable for generating docs/ API refs.

    Throwing a parser into the mix means you can create you own "object literals" from non-JSON formats like XML, YAML, or CSV. It's also great for HTML templates, especially complex HTML with nested quoted attributes, no more leaning toothpick syndrome...

    Let's get to the code eh? first off, a simple inline code version, boilerplate in red, arbitrary string data in green:


    Code:
    function feedbackForm(){
      var ts=feedbackForm.toString();
      return ts.slice(ts.indexOf("/"+"*")+2, ts.lastIndexOf("*"+"/"));/*
    
    
    <form action= "/api"  method="POST" >
      <label for="search">	  Search	
             <input  placeholder="enter search term" required type='search'  name='term'  />	
        </label>
    </form>	
    
    */
    }
    
    alert( feedbackForm()  );
    you can copy the red code into any function, to turn the function into a string container.


    if you want to do this a lot, save yourself the cut and paste using a function prototype method:


    Code:
    Function.prototype.toText=function(){
      var s=String(this);
      return s.slice(s.indexOf("/*")+2, s.lastIndexOf("*/"));
    };
    
    
    
    function feedbackForm(){/*
    
     <form action= "/api"  method="POST" >
        <label for="search">	  Search	
             <input  placeholder="enter search term" required type='search'  name='term'  />	
        </label>
     </form>	
    
    
    */}
    
    alert(  feedbackForm.toText()   );
    in this case, you don't need any actual code inside the function, only the comment indicators (/*,*/) and the actual data.


    you can extend this notion to create self-unpacking functions, for example a CSV can become an array of objects:

    Code:
    Function.prototype.toText=function(){
      var s=String(this);
      return s.slice(s.indexOf("/*")+2, s.lastIndexOf("*/"));
    };
    
    
    
    //this helper turns CSVs into arrays of objects for us
    function parseCSVStrong(str){
    	var  stack=[], ob=[], float="", inQuotes=false;
    	function addCell(){ ob.push(cast(float.trim())); float=""; }
    	function cast(v){var builtIn=cast.lut[v];return !isNaN(Number(v))? Number(v): (builtIn!==undefined?builtIn:v)||"";}; 
    		cast.lut=({ 'true':true, 'false':false,"":null});
    	for( var i=0; i<str.length;i++){
    	 	var it=str[i];
    		if(it==='"'){  inQuotes=!inQuotes; if(str[i-1]==='"'){ float+='"';} continue; }
    		if(it==="\t"){ if(!inQuotes){addCell();}else{float+="\t";} continue;}
    		if(it==="\n"){ addCell(); stack.push(ob); ob=[]; continue;}
    		float+=it;
    	}
    	addCell(); 
    	stack.push(ob);
            var h=stack[0];
            return stack.map(function(a,b){ var o={}; h.map(function(aa,bb){o[h[bb]]=a[bb];}); return o; }).slice(1)
    }
    now, use these two little helpers to store bulk CSV data in a function:

    Code:
    var myCSV=(function(){return parseCSVStrong(arguments.callee.toText())/*Contract No	Vendor	Description	Start Date	End Date	Expended Amount	Total Amount
    15608	TEXAS MUNICIPAL LEAGUE	Insurance Premiums	5/9/2000	9/30/2013	28661067.89	38043203
    17030	STARTRAN, INC.	ILA - Startran Agreement	12/31/1991	12/31/2200	0	1
    23715	LOWER COLORADO RIVER AUTHORITY	ILA - Land Mobile Radio Services, Equip & Installation	6/28/2001	6/28/2013	8080108.5	13570149.37
    28890	CITY OF AUSTIN	ILA - Build a Greater Austin: Regional Mobility Project	6/22/2001	9/30/2013	39280461.7	42720086
    29165	URBAN TRANSPORTATION ASSOCIATION INC	Automatic Passenger Counter (APC) System	3/13/2002	9/30/2013	1705249.93	1738813.28
    39608	AUSTIN ENERGY	ILA -  Energy Conservation Services	5/15/2003	5/14/2013	60465.18	230000
    50766	CITY OF AUSTIN	ILA - 1/4 cent Sales Tax Refund	3/1/2003	9/30/2024	73714012.77	110868366
    55996	CITY OF AUSTIN	ILA - City of Austin: CTECC/Communications & Technology Management	8/14/2010	8/13/2013	3852129.8	4470239.1
    65877	UNIVERSITY OF TEXAS	ILA - UT: Faculty & Staff Transportation	9/1/2012	8/31/2015	0	0
    75047	BRIGHT HORIZONS FAMILY SOLUTIONS	Child Care and Learning Center	6/1/2006	6/1/2013	4013165.14	4284729.58
    76995	BRIDGESTONE/FIRESTONE INC	Tire Leasing and Maintenance	8/29/2009	8/18/2015	5270535.13	5631393.21
    81680	ULTIMATE SOFTWARE	Payroll and Human Resources Information Management	3/12/2007	3/31/2014	1215284.22	1380467
    83824	EVINS PERSONNEL CONSULTANTS INC	Primary Temporary Services	5/22/2007	5/21/2013	2968763.96	3273978
    83825	KEYSTAFF	Primary Temporary Services	5/22/2007	5/21/2013	1891203.5	2576000
    85986	RAILCOMM, LLC	Dispatch Control System for TWC & CTC	8/22/2007	1/1/2014	2331614.24	2331614.24
    86207	TEXAS DEPT OF TRANSPORTATION	ILA - Non-Profit Van Services	8/1/2007	7/31/2013	0	0
    86710	ALLIEDBARTON SECURITY SERVICES	Unarmed Security Services	10/1/2007	5/6/2013	4691124.75	5755443.84
    88302	DOUCET & ASSOCIATES INC	Professional Surveying Services, Task Order Rotation	11/20/2007	6/30/2013	750900.06	900500
    88423	WESTON SOLUTIONS, INC	Environmental Engineering Services, Task Order	12/14/2007	7/13/2013	206970.22	4000000*/}());
    
    
    //view the parsed array of object's first element:
    alert(
      JSON.stringify(
        myCSV[0] , null, "\t"
     )
    );
    which shows:
    Code:
    {
    	"Contract No": 15608,
    	"Vendor": "TEXAS MUNICIPAL LEAGUE",
    	"Description": "Insurance Premiums",
    	"Start Date": "5/9/2000",
    	"End Date": "9/30/2013",
    	"Expended Amount": 28661067.89,
    	"Total Amount": 38043203
    }


    one last use: injecting css from scripts without tons of camelCase conversion or string escaping:




    Code:
    //our two little friends:
    Function.prototype.toText=function(){
      var s=String(this);
      return s.slice(s.indexOf("/*")+2, s.lastIndexOf("*/"));
    };
    
    function addCSS(iCSS) {
    	var D = document, h = D.getElementsByTagName("head")[0], ns = D.createElement("style");
    	return h.appendChild(ns).innerHTML = iCSS;
    } 
    
    
    //now we're just a heartbeat away from lots of pretty CSS:
    (function(){ return addCSS(arguments.callee.toText())/*
    
    html {
    	color : #000;
    	background : #FFF;
    }
    
    table {
    	border-collapse : collapse;
    	border-spacing : 0;
    }
    
    fieldset, img {
    	border : 0;
    }
    
    address, caption, cite, code, dfn, em, strong, th, var {
    	font-style : normal;
    	font-weight : normal;
    }
    
    ol, ul {
    	list-style : none;
    }
    
    caption, th {
    	text-align : left;
    }
    
    h1, h2, h3, h4, h5, h6 {
    	font-size : 100%;
    	font-weight : normal;
    }
    
    q:before, q:after {
    	content :'';
    }
    
    abbr, acronym {
    	border : 0;
    	font-variant : normal;
    }
    
    
    */}());
    that automatically injects the css inside the function into the document.
    you can name the same function and call it as needed if you don't always need to inject it, it's just an example of how to store text-ish data in JS without a lot of maintenance-preventing escaping and packaging.

    one caveat with CSS is that you have to strip out all the comments, since they are the same as JS comments.
    you can use danml.com/slim to "parse css" and "pretty css", which should remove comments and format the whitespace respectively.


    in summation, there are 1,001 use for this, and it's really nice not to have to mess around with IE conditional comments or XML hacks like the OP; all browsers work the same now, use without fear.
    Last edited by rnd me; 06-04-2013 at 10:16 PM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • The Following 2 Users Say Thank You to rnd me For This Useful Post:

    jmrker (06-06-2013), niralsoni (06-05-2013)

  • #7
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,102
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Question

    Question:
    I was trying to understand and implement you last bit of code (addCSS)
    Although it is "mostly" cut and paste, it does not work as I expect,
    but it's probably something I've done to cause the problem. Am I implementing it wrong?

    Could you peek at it and comment about where I've gone wrong?
    I had expected 6 different heading, but I see only one size.
    Code:
    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="UTF-8" />
    
    <title> Add CSS test </title>
    <script type="text/javascript">
    //our two little friends:
    Function.prototype.toText=function(){
      var s=String(this);
      return s.slice(s.indexOf("/*")+2, s.lastIndexOf("*/"));
    };
    
    function addCSS(iCSS) {
    	var D = document, h = D.getElementsByTagName("head")[0], ns = D.createElement("style");
    	return h.appendChild(ns).innerHTML = iCSS;
    } 
    
    //now we're just a heartbeat away from lots of pretty CSS:
    (function(){ return addCSS(arguments.callee.toText())/*
    
     html {	color : #000;  background : #FFF; }
     table { border-collapse : collapse;  border-spacing : 0; }
     fieldset, img { border : 0; }
     address, caption, cite, code, dfn, em, strong, th, var {
    	font-style : normal;
    	font-weight : normal;
     }
     ol, ul { list-style : none; }
     caption, th { text-align : left; }
     h1, h2, h3, h4, h5, h6 { font-size : 100%; font-weight : normal; }
     q:before, q:after { content :''; }
     abbr, acronym { border : 0;  font-variant : normal; }
    
    */}());
    
    </script>
    
    </head>
    <body>
    <h1> H1 test </h1>
    <h2> H2 test </h2>
    <h3> H3 test </h3>
    <h4> H4 test </h4>
    <h5> H5 test </h5>
    <h6> H6 test </h6>
    </body>
    </html>

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    Quote Originally Posted by jmrker View Post
    Question:
    I was trying to understand and implement you last bit of code (addCSS)
    Although it is "mostly" cut and paste, it does not work as I expect,
    but it's probably something I've done to cause the problem. Am I implementing it wrong?

    Could you peek at it and comment about where I've gone wrong?
    I had expected 6 different heading, but I see only one size.
    you have them set for the same size, 100%. the margins do flux, so the CSS is working. this is probably more clear if you include some different rules:

    Code:
     h1, h2, h3, h4, h5, h6 { font-size : 100%; font-weight : normal; }
     h1  { color: red;}
      h2 { color: blue; }
      h3 { color: green;  }
    when i test in firefox, it worked fine. The addCSS method itself is not 100% cross browser, i know IE7 hates it, i just tested in FF and chrome since it's not the main point of my post.

    i do have a much longer, less demo-friendly, more bullet-proof addCSS if you need it:

    Code:
    function addCSS(iCSS) {
    	var vi = "adds a css tyle section to the document, filled with text like an external stylesheet";
    	var D = document;
    	var h = D.getElementsByTagName("head");
    	if (!h[0]) {
    		return;
    	} /* end if */
    
    	var ns = document.createElement("style");
    	ns.type = "text/css";
    	h[0].appendChild(ns);
    	try {
    		if (ns.styleSheet && ns.styleSheet.cssText) {
    			ns.styleSheet.cssText = iCSS;
    			return;
    		} /* end if(ns.styleSheet && ... */
    
    		ns.innerHTML = iCSS;
    	} catch (e3) {
    		try {
    			ns.appendChild(document.createTextNode(iCSS));
    		} catch (e3) {}
    	} /* end try/catch */
    
    } /* end addCSS() */


    Apparent issue aside, thanks for checking this out. i was super excited last month when FF switched; i've been waiting 6 years for this, and now it's here.
    I will be writing other cool stuff with it; maybe coffeescript right in the js file, or a prototype method to turn a js function into a coffeescript method. Or maybe just some coffee-script-like enhancements without the full burden of a big parser. anyway, i'm glad the language can be safely expanded now that firefox's is onboard. now if only i could compress/minify this code as well...
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #9
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,102
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Question

    Quote Originally Posted by rnd me View Post
    you have them set for the same size, 100%. the margins do flux, so the CSS is working. this is probably more clear if you include some different rules:

    Code:
     h1, h2, h3, h4, h5, h6 { font-size : 100%; font-weight : normal; }
     h1  { color: red;}
      h2 { color: blue; }
      h3 { color: green;  }
    when i test in firefox, it worked fine. The addCSS method itself is not 100% cross browser, i know IE7 hates it, i just tested in FF and chrome since it's not the main point of my post.

    i do have a much longer, less demo-friendly, more bullet-proof addCSS if you need it:

    Code:
    ...


    Apparent issue aside, thanks for checking this out. i was super excited last month when FF switched; i've been waiting 6 years for this, and now it's here.
    I will be writing other cool stuff with it; maybe coffeescript right in the js file, or a prototype method to turn a js function into a coffeescript method. Or maybe just some coffee-script-like enhancements without the full burden of a big parser. anyway, i'm glad the language can be safely expanded now that firefox's is onboard. now if only i could compress/minify this code as well...
    I was just using your original values for the H1 thru H6 CSS setting.
    I was not sure why the font-size setting so it appeared to do nothing special.

    If you have the time, could you explain the code settings in the function you supplied?
    Code:
    (function(){ return addCSS(arguments.callee.toText())/*
    
     html {	color : #000;  background : #FFF; }
     table { border-collapse : collapse;  border-spacing : 0; }
     fieldset, img { border : 0; }
     address, caption, cite, code, dfn, em, strong, th, var {
    	font-style : normal;
    	font-weight : normal;
     }
     ol, ul { list-style : none; }
     caption, th { text-align : left; }
     h1, h2, h3, h4, h5, h6 { font-size : 100%; font-weight : normal; }
     q:before, q:after { content :''; }
     abbr, acronym { border : 0;  font-variant : normal; }
    
    */}());
    Some questions...
    What are the 'q' setting used for?
    Why set the border:0 for abbr and acronym? I thought they were defaulted to 0 anyway.
    Why are you setting the 'strong' to 'normal' style and weight?
    Finally, what is the 'coffee-script-like enhancement' and 'coffeescript method" of which you speak?

  • #10
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,401
    Thanks
    11
    Thanked 595 Times in 575 Posts
    Quote Originally Posted by jmrker View Post
    I was just using your original values for the H1 thru H6 CSS setting.
    I was not sure why the font-size setting so it appeared to do nothing special.

    If you have the time, could you explain the code settings in the function you supplied?
    ..............................
    Some questions...
    What are the 'q' setting used for?
    Why set the border:0 for abbr and acronym? I thought they were defaulted to 0 anyway.
    Why are you setting the 'strong' to 'normal' style and weight?
    Finally, what is the 'coffee-script-like enhancement' and 'coffeescript method" of which you speak?
    First off, don't stare too hard at the CSS here, it's just some reset css i grabbed from one of the sites at work. It's supposed to make all browsers looks the same given the same HTML and no more CSS. You build on top of this uniform, if under-styled, foundation. That makes sure that there are no suprises from the default or "user agent" CSS that the browser applies to all sites.

    the q settings are to strip the quote marks off of <q> tags, which some browsers apply.

    strong has different default styles in different browsers, some weight 400, some 600, etc. This makes them all look the same.
    the border value is the same sort of thing.

    again, this is just some demo CSS, the point of which is more "look mom no quotes or slashes" than "here's some awesome CSS"...






    Regarding Coffeescript.
    I have mixed feelings about CoffeeScript, so i hesitate to puiblish this, since it might only encourage its use. Still, it's a lot better than the other fake languages like TypeScript and Dart. If it gets something made that otherwise wouldn't have been made, i guess that's a good thing. Still, most of the enthusiasm around coffeescript comes from people who don't know JS.

    Here's a Typical Example of this: http://iamproblematic.com/2012/03/06...-coffeescript/
    I don’t like JavaScript. I think it’s ugly, I think it’s too verbose (`typeof foo !== “undefined” && foo !== null` makes me die a little inside),
    when, if(foo!=null), does exactly what his verbose code does. poor fool.

    Anyway, coffescript.

    It's pretty cool, but it's a PITA to have to compile you code into JavaScript. The other option to early compilation is in-browser compilation. That's not terrible, it parses pretty fast, but it has one MAJOR drawback: it must be delivered as a string instead of a function.

    Typically, people use off-type <script> tags or ajax to fetch these scripts. That's poor for a few reasons:
    1. one more delay before usability
    2. inline <script>s have long been frowned upon by pro web devs
    3. ajax is not meant for grabbing code, and eval() leaves behind no script tag
    4. harder to load resources in the right order for depends and callbacks


    Idealy, one could use CoffeeScript right along side other JS code, instead of a special routine just for one part of the app. Well folks, this comment thing is the way to do that...


    CoffeeScript running in a plain-old <script> file with other plain JS:

    Code:
    function addScript(u) {
    	var sc2 = document.createElement('script');
    	sc2.src = u;
    	document.getElementsByTagName('head')[0].appendChild(sc2);
    }
    
    function required(modules){ 
    	var list=[].join.call(arguments, ",");
    	addScript("http://danml.com/js/?"+ list.concat(",complete")); 
    	return function(ready){ _requiredCB=function(){ready(modules)};};
     }
    
    Function.prototype.toText=function(){
    	  var s=String(this);
    	  return s.slice(s.indexOf("/*")+2, s.lastIndexOf("*/"));
    };
    
    
    required("coffeescript")(function demo(){ 
        return CoffeeScript.eval(demo.toText()); /*	
    	
    	# Functions:
    	square = (x) -> x * x
    	
    	# Arrays:
    	list = [1, 2, 3, 4, 5]
    	
    	# Array comprehensions:
    	cubes = (square num for num in list)
    	
    	alert cubes
    
    */});//end coffeescript demo
    this demo, stripped from the coffeescript homepage, simply alerts "1,4,9,16,25", but it gets that value by using a coffeescript function upon a private coffescript list, using coffeescript Array comprehension syntax.

    Again, i don't know what you call this pattern, i'm open to ideas, but i think it's pretty cool...
    Last edited by rnd me; 06-12-2013 at 02:16 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/9/03) IE7:0.1, IE8:4.6, IE11:9.1, IE9:3.1, IE10:3.0, FF:17.2, CH:46, SF:11.4, NON-MOUSE:38%

  • #11
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,102
    Thanks
    38
    Thanked 498 Times in 492 Posts
    Thank you for the explanations.
    Without the context of the solution it was difficult to understand the purpose of the suggested changes.

    I'll look forward to other possible uses of this function.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •