通过 JS 自执行函数在 Head 中创建文本节点时遇到问题

Posted

技术标签:

【中文标题】通过 JS 自执行函数在 Head 中创建文本节点时遇到问题【英文标题】:Trouble Creating Text Node in Head via JS Self-Executing Function 【发布时间】:2014-12-26 20:10:30 【问题描述】:

这是我第一次使用自动执行的匿名函数,但是,我相信我错过了一些基本的和就在我面前的东西。本质上,我试图通过函数'writeFontFace()'传递一个参数,并让它在我的文档头部写入以下代码,如下所示:

@font-face 
    font-family: 'arrows';
    src: url('fonts/arrows/arrows.eot?');
    src: url('fonts/arrows/arrows.eot?#iefix') format('embedded-opentype'),
         url('fonts/arrows/arrows.woff?') format('woff'),
         url('fonts/arrows/arrows.ttf?') format('truetype'),
         url('fonts/arrows/arrows.svg?#arrows') format('svg');
    font-weight: normal;
    font-style: normal;

现在,如果我在此函数 (writeFontFace) 末尾取消注释“return”语句,我确实收到了我期望收到的适当输出,但是(无论出于何种原因),它不会附加 '我的文档头部内的脚本变量(包含前面提到的@font-face 定义)?不能完全弄清楚为什么。任何建议和/或 cmets 都将不胜感激……再说一次,这是我第一次使用自动执行的匿名函数,因此,如果有人觉得他们可能有一些建设性的批评,我将不胜感激和/或建议。与往常一样,提前非常感谢。

~干杯

自执行匿名函数

(function() 

     /**
      * Object Literal           Property Values           Constant: property values to be used throughout this object
      */
      const vars = 
           decCharPrefix : '&#',
           decCharSuffix : ';',
           baseGlyphValue: 59392,
         
     ;

     /**
      * bpIconFont               Constructor               Core: constructor for this library; ensures that this library is instantiated if an internal method is called
      */
     var bpIconFont = function() 
         if(!(this instanceof bpIconFont))
             return new bpIconFont();
     ;

     /**
      * bpIconFont.fn
      */
     bpIconFont.fn = bpIconFont.prototype = 
         init: function() 
             console.log('bpIconFont Initialized!');
         
     

     window.bpIconFont = bpIconFont;                         // Expose: anonymous self-executing function to DOM

)();

/**
 * getFontDirectroy         Method                    Gets: generates the directory to which the passed font will be placed, via relative path
 * @param                   Array/String font         Converts: the passed array or string and generates a 'relative path' for the desired font
 * @return                  Array/String              Returns: the relative path for the font
 */
bpIconFont.fn.getFontDirectroy = function(font) 
    var fontDir = 'fonts/' + font + '/';
    return fontDir;
;

/**
 * getFontDirectroy         Method                    Gets: generates the directory to which the passed font will be placed, via relative path
 * @param                   Array/String font         Converts: the passed array or string and generates a 'relative path' for the desired font
 * @return                  Array/String              Returns: the relative path for the font
 */
bpIconFont.fn.writeFontFace = function(font) 
    var dir    = bpIconFont().getFontDirectroy(font);
    var head   = document.getElementsByTagName("head")[0];
    var script = document.createElement('style');
        script.setAttribute('type', 'text/css');

    var fontFace = '@font-face ' +
                  '\n\tfont-family: \'' + font +
                '\';\n\tsrc: url(\'' + dir + font + '.eot?\');' +
                   '\n\tsrc: url(\'' + dir + font + '.eot?#iefix\') format(\'embedded-opentype\'),' +
                     '\n\t\t url(\'' + dir + font + '.woff?\') format(\'woff\'),' +
                     '\n\t\t url(\'' + dir + font + '.ttf?\') format(\'truetype\'),' +
                     '\n\t\t url(\'' + dir + font + '.svg?#' + font + '\') format(\'svg\');' +
                   '\n\tfont-weight: normal;' +
                   '\n\tfont-style: normal;' +
                '\n';

    script.appendChild(document.createTextNode(fontFace));

    head.appendChild(script);

    // return fontFace;
;

【问题讨论】:

【参考方案1】:

基本上,如果其他人遇到类似问题,下面的代码应该会为您提供适当的修复:

(function() 

     /**
      * bpIconFont               Constructor               Core: constructor for this library; ensures that this library is instantiated if an internal method is called
      */
     var bpIconFont = function() 
         if(!(this instanceof bpIconFont))
         return new bpIconFont();
     ;

     /**
      * bpIconFont.fn
      */
     bpIconFont.fn = bpIconFont.prototype = 
         init: function() 
             console.log('bpIconFont Initialized!');
         
     

     window.bpIconFont = bpIconFont;                         // Expose: anonymous self-executing function to DOM

)();

     /**
      * Object Literal           Property Values           Constant: property values to be used throughout this object
      */
    vars = 
        decCharPrefix : '&#',
        decCharSuffix : ';',
        baseGlyphValue: 59392,
    ;

/**
 * getFontDirectroy         Method                    Gets: generates the directory to which the passed font will be placed, via relative path
 * @param                   Array/String font         Converts: the passed array or string and generates a 'relative path' for the desired font
 * @return                  Array/String              Returns: the relative path for the font
 */
bpIconFont.fn.getFontDirectroy = function(font) 
    var fontDir = 'fonts/' + font + '/';
    return fontDir;
;

/**
 * getFontDirectroy         Method                    Gets: generates the directory to which the passed font will be placed, via relative path
 * @param                   Array/String font         Converts: the passed array or string and generates a 'relative path' for the desired font
 * @return                  Array/String              Returns: the relative path for the font
 */
bpIconFont.fn.writeFontFace = function(font) 
    var dir    = bpIconFont().getFontDirectroy(font);
    var head   = document.getElementsByTagName("head")[0];
    var script = document.createElement('style');
        script.setAttribute('type', 'text/css');

    var cssDef = '\ndiv#output-window ' +
                 '\n\tfont-family:\'' + font + '\';' +
                 '\n';

    var fontFace = '@font-face ' +
                  '\n\tfont-family: \'' + font +
                '\';\n\tsrc: url(\'' + dir + font + '.eot?\');' +
                   '\n\tsrc: url(\'' + dir + font + '.eot?#iefix\') format(\'embedded-opentype\'),' +
                     '\n\t\t url(\'' + dir + font + '.woff?\') format(\'woff\'),' +
                     '\n\t\t url(\'' + dir + font + '.ttf?\') format(\'truetype\'),' +
                     '\n\t\t url(\'' + dir + font + '.svg?#' + font + '\') format(\'svg\');' +
                   '\n\tfont-weight: normal;' +
                   '\n\tfont-style: normal;' +
                '\n';

    script.appendChild(document.createTextNode(fontFace));
    script.appendChild(document.createTextNode(cssDef));
    head.appendChild(script);

;

【讨论】:

以上是关于通过 JS 自执行函数在 Head 中创建文本节点时遇到问题的主要内容,如果未能解决你的问题,请参考以下文章

如何在节点 js 中创建类似 php 的函数

js中创建函数的三种方式及区别

如何在 onlyoffice 中创建用于 .xlsx 的自定义函数

如何在 Vue.js 中创建自定义链接组件?

如何在 Sequelize 中的导入模型中创建自定义方法或函数

在 JavaScript 中创建自定义回调