Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic CSS and JS loading

DHTML

Dynamic CSS and JS loading

by  dkdude  Posted    (Edited  )
This is one way of loading dynamic CSS and JS. It takes a few files to complete my example, but they all rely on the [tt]loader.js[/tt].

Here we go ...

Let look at at basic xhtml document with a few [color red]extensions[/color]:

[tt]index.html[/tt]

Code:
[b]<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Dynamic Script &amp Style Loader</title>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="[color red]baseline.css[/color]" />
  <script type="text/javascript" src="[color red]generic.js[/color]"></script>
  <script type="text/javascript" src="[color red]loader.js[/color]"></script>
  <script type="text/javascript" src="[color red]debug.js[/color]"></script>
</head>
  <body>
    <h3>
      My Dynamic Script &amp; Style Loader
    </h3>
    <hr />
    <h4>Let's change styles!</h4>
    <p>
      <button onclick="load_stylesheet('[color red]verdana.css[/color]')">
        Load the verdana.css stylesheet
      </button>
      <br />
      <button onclick="load_stylesheet('[color red]arial.css[/color]')">
        Load the arial.css stylesheet
      </button>
      <br />
      <button onclick="load_stylesheet('[color red]impact.css[/color]')">
        Load the impact.css stylesheet
      </button>
    </p>
    <hr />
    <h4>
      We can change scripts too!
    </h4>
    <p>
      <button onclick="hello()" id="myButton">
        I say &quot;Hello world!!&quot;
      </button>
      <br />
      <button onclick="load_script('[color red]hello.js[/color]')">
        Change the function of that button &nbsp; <b>&uarr;</b>
      </button>
    </p>
    <hr />
    <button onclick="[color red]stat()[/color]">
      Watch the Dynamic Load History
    </button>
  </body>
</html>[/b]

The document has a baseline-styling for the buttons:

[tt]baseline.css[/tt]
Code:
[b]body {
  text-align	: center;
}

button {
  width		: 300px;
  padding		: 5px;
  margin		: 10px;
}[/b]

This is quite basic xhtml. And this document uses a few JavaScript extensions.

One is a gereric "hello world" script (which we will be replacing dynamically):

[tt]generic.js[/tt]

Code:
[color gray]//---------------------------------------------------------------------------
//    The classic 'Hello World' :
//---------------------------------------------------------------------------[/color][b]
function hello() {
  alert('Hello world!!');
}
[/b]

Now, let's have a look at the actual Script & Stylesheet loader :

[tt]loader.js[/tt]
Code:
[color gray]//---------------------------------------------------------------------------
//    Check to see if dubugging is enabled :
//---------------------------------------------------------------------------
[/color][b]if(!eval(debug)==true)
  var debug = false;;


[/b][color gray]//---------------------------------------------------------------------------
//    Let's load some JavaScripts :
//---------------------------------------------------------------------------
[/color][b]function load_script(filename) {
  var script = document.createElement('script'); 
  script.type = 'text/javascript'; 
  script.src = filename; 
  document.getElementsByTagName('head')[0].appendChild(script);
  if(debug)
    monitor(dynScripts, filename);
}


[/b][color gray]//---------------------------------------------------------------------------
//    Let's load some Stylesheets :
//---------------------------------------------------------------------------
[/color][b]function load_stylesheet(filename) {
  var css = document.createElement('link'); 
  css.rel = 'stylesheet'; 
  css.type = 'text/css'; 
  css.href = filename; 
  document.body.appendChild(css);
  if(debug)
    monitor(dynStyles, filename);
}


[/b][color gray]//---------------------------------------------------------------------------
//    Watch the status - IF enabled :
//---------------------------------------------------------------------------
[/color][b]function stat() {
  [/b][color gray]// IF debugging is enabled, then dump via the dynStatus() function :[/color][b]
  if(debug)
    dynStatus();
  [/b][color gray]// ELSE say that debugging is disabled ::[/color][b]
  else
    alert('Debug not enabled');
}
[/b]

Here's the three sample stylesheets that are (or can be) dynamic loaded:

[tt]verdana.css[/tt]

Code:
[b]h3 {
  font-family           : verdana;
  font-size             : 22px;
  font-weight           : bold;
  color                 : #202020;
  letter-spacing        : 5px;
}

body {
  background-color      : #7DA177;
}[/b]

[tt]arial.css[/tt]

Code:
[b]h3 {
  font-family           : arial;
  font-size             : 22px;
  font-weight           : bold;
  color                 : #EAEAEA;
  letter-spacing        : 5px;
}

body {
  background-color      : #4B6697;
}[/b]

and fianlly [tt]impact.css[/tt]

Code:
[b]h3 {
  font-family           : impact;
  font-size             : 22px;
  font-weight           : normal;
  color                 : #404040;
  letter-spacing        : 5px;
}

body {
  background-color      : #F8E488;
}[/b]

Now, let's replace the generic hello world message:

[tt]hello.js[/tt]

Code:
[color gray]//---------------------------------------------------------------------------
//    Fetch the button that's about to change function :
//---------------------------------------------------------------------------
[/color][b]var myButton = document.getElementById('myButton');


[/b][color gray]//---------------------------------------------------------------------------
//    Change the label of it :
//---------------------------------------------------------------------------
[/color][b]myButton.innerHTML = 'I now say &quot;Hello YOU!!&quot;';


[/b][color gray]//---------------------------------------------------------------------------
//    Change the background-color of it :
//---------------------------------------------------------------------------
[/color][b]myButton.style.backgroundColor = '#000000';


[/b][color gray]//---------------------------------------------------------------------------
//    Change the text color of it :
//---------------------------------------------------------------------------
[/color][b]myButton.style.color = '#EAEAEA';


[/b][color gray]//---------------------------------------------------------------------------
//    Change the font-weight of it :
//---------------------------------------------------------------------------
[/color][b]myButton.style.fontWeight = 'bold';


[/b][color gray]//---------------------------------------------------------------------------
//    Replacement hello() message for the button :
//---------------------------------------------------------------------------
[/color][b]function hello() {
  alert('Hello YOU!!');
}[/b]

Finally, as an option, you can include the debugger (like in my example index.html):

[tt]debug.js[/tt]

Code:
[color gray]//---------------------------------------------------------------------------
// Global debugging variable :
//---------------------------------------------------------------------------
[/color][b]var debug = true;


[/b][color gray]//---------------------------------------------------------------------------
// Global Dynamic Script Name Monitor Array :
//---------------------------------------------------------------------------
[/color][b]var dynScripts = new Array();


[/b][color gray]//---------------------------------------------------------------------------
// Let's add a label to it :
//---------------------------------------------------------------------------
[/color][b]dynScripts[0] = '\n\nDynamic Scripts History:\n====================';


[/b][color gray]//---------------------------------------------------------------------------
// Global Dynamic Stylesheet Name Monitor Array :
//---------------------------------------------------------------------------
[/color][b]var dynStyles = new Array();


[/b][color gray]//---------------------------------------------------------------------------
// Let's add a label to it :
//---------------------------------------------------------------------------
[/color][b]dynStyles[0] = 'Dynamic Styles History:\n====================';


[/b][color gray]//---------------------------------------------------------------------------
// Log the loaded module names :
//---------------------------------------------------------------------------
[/color][b]function monitor(myArray, value) {
  var next = myArray.length;
  myArray[next] = value;
}


[/b][color gray]//---------------------------------------------------------------------------
// Alert the status - IF debugging is enabled :
//---------------------------------------------------------------------------
[/color][b]function dynStatus() {
  [/b][color gray]// Split array elements into seperate lines :[/color][b]
  var output = dynStyles.concat(dynScripts).join('\n');
  alert(output);
}[/b]

Hope you find this FAQ useful ...

Happy coding!
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top