Loading external CSS files

You can define styles in an external CSS file and then load that file into a style sheet object. The styles defined in the CSS file are added to the style sheet object. To load an external CSS file, you use the load() method of the TextField.StyleSheet class. To determine when the CSS file has finished loading, use the style sheet object's onLoad event handler.

In the following example, you'll create and load an external CSS file and use the TextField.StyleSheet.getStyleNames() method to retrieve the names of the loaded styles.

To load an external style sheet:

  1. In your preferred text or XML editor, create a file.
  2. Add the following style definitions to the file:
    // Filename: styles.css
    bodyText {
      font-family: Arial,Helvetica,sans-serif;
      font-size: 12px;
    }
    
    headline {  
      font-family: Arial,Helvetica,sans-serif;
      font-size: 24px;
    }
    
  3. Save the CSS file as styles.css.
  4. In Flash, create a FLA document.
  5. In the Timeline (Window > Timeline), select Layer 1.
  6. Open the Actions panel (Window > Development Panels > Actions).
  7. Add the following code to the Actions panel:
    var css_styles = new TextField.StyleSheet();
    css_styles.load("styles.css");
    css_styles.onLoad = function(ok) {
      if(ok) {
        // display style names
        trace(this.getStyleNames());
      } else {
        trace("Error loading CSS file.");
      }
    }
    
  8. Save the file to the same directory that contains styles.css.
  9. Test the movie (Control > Test Movie).

    You should see the names of the two styles displayed in the Output panel:

    body
    headLine
    

    If you see "Error loading CSS file" displayed in the Output panel, make sure the FLA file and the CSS file are in the same directory and that you typed the name of the CSS file correctly.

As with all other ActionScript methods that load data over the network, the CSS file must reside in the same domain as the SWF file that is loading the file. (See About allowing cross-domain data loading.)