【问题标题】:Embed HTML/JS code on page and execute在页面上嵌入 HTML/JS 代码并执行
【发布时间】:2014-05-17 02:10:20
【问题描述】:

我有一个嵌入的 javascript,并在这样的页面上

<script type="text/javascript" src="site.com/myscript.js"></script>

上面的代码应该返回一个 HTML sn-p,它可以包含常规 HTML、javascript 内容(在 &lt;script&gt; &lt;/script&gt; 标签内,或者也像 &lt;script src="other_sources.js" TYPE="text/javascript"&gt;&lt;/script&gt; 这样的代码

我正在使用类似的东西在页面上显示代码。

document.write('<div id="displayAd"></div');
document.getElementById("displayAd").innerHTML = "{code here}";

这会将内容放在页面上,但不会执行脚本 src 或添加到代码上的脚本。知道怎么做吗?

【问题讨论】:

    标签: javascript


    【解决方案1】:

    脚本标签将为您提供 javascript,而不是 HTML 内容、javascript 和其他脚本标签的杂乱无章。只要您定义了单独的部分,您就可以使用纯 javascript 来获得您想要的东西。例如,您的 myscript.js 可能如下所示:

    (function (win) {
        var MYAPP,
            adIndex = 0,
            srcIndex = 0,
            html,
            srcs;
    
        //helper function to load scripts
        //JavaScript Patterns book
        function require(file, callback) {
            var script = document.getElementsByTagName('script')[0],
                newjs = document.createElement('script'),
                calledBack = false;
    
            if (typeof callback !== "function") {
                //noop
                callback = function () {};
            }
    
                // IE
            newjs.onreadystatechange = function () {
                if (newjs.readyState === 'loaded' || newjs.readyState === 'complete') {
                    newjs.onreadystatechange = null;
                    if (!calledBack) {
                        callback();
                        calledBack = true;
                    }
                }
            };
    
            // others
            newjs.onload = function () {
                if (!calledBack) {
                    callback();
                    calledBack = true;
                }
            };
    
            newjs.src = file;
            script.parentNode.insertBefore(newjs, script);
        }
    
        //variable for html content and external scripts
        win.MYAPP = win.MYAPP || {
            html: [],
            srcs: []
        };
    
        MYAPP = win.MYAPP;
        html = MYAPP.html;
        srcs = MYAPP.srcs;
    
        //Add some HTML content to MYAPP.html
        html.push('<div>AD CONTENT HERE</div>');
        html.push('<div>ANOTHER AD HERE</div>');
    
        //Other external sources that will be loaded async... Array of objects with file and optional callback to run
        //when loaded.
        srcs.push({file: 'http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js', callback: DoWork});
    
        //Load the scripts
        for (srcIndex = 0; srcIndex < srcs.length; srcIndex++) {
            require(srcs[srcIndex].file, srcs[srcIndex].callback);
        }
    
        //Do stuff with HTML content
        var displayAd = document.createElement("div");
        displayAd.innerHTML = html[adIndex];
        adIndex = (adIndex + 1) % html.length;
        document.body.appendChild(displayAd);
        //Rotate Ads every 3 seconds.
        window.setInterval(function () {
            var len = html.length;
            if (len && adIndex <= len) {
                displayAd.innerHTML = html[adIndex];
                adIndex = (adIndex + 1) % len;
            }
        }, 3000);
    
        //Sample callback function to be executed after script is loaded
        function DoWork() {
            win.$(function () {
                win.alert('Jquery loaded');
            });
        }
    
    }(window));
    

    我尝试坚持使用纯 js 实现。 MYAPP 包含两个感兴趣的属性。要“推入”动态创建的 displayAd div 的 html 内容数组,以及要包含要包含的外部脚本数组的 srcs。您需要提供一个可选的回调,以防您想在脚本加载后使用它(例如 DoWork)。这是一个jsfiddle 示例。

    有些库可以很好地处理更多此类问题(例如 requirejs)以加载外部依赖项,但再次希望提供与库无关的方法。

    【讨论】:

      猜你喜欢
      • 2011-12-13
      • 2017-10-16
      • 2017-03-14
      • 1970-01-01
      • 2021-09-14
      • 2022-06-18
      • 1970-01-01
      • 2015-11-09
      • 2016-11-10
      相关资源
      最近更新 更多