在页面上嵌入HTML / JS代码并执行

时间:2014-05-16 14:39:23

标签: javascript

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

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

上面的代码应该返回一个HTML代码段,其中可以包含常规的HTML,javascript内容(在<script> </script>个标记内部,或者还包含<script src="other_sources.js" TYPE="text/javascript"></script>

之类的代码

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

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

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

1 个答案:

答案 0 :(得分:1)

脚本标记将为您提供javascript,而不是HTML内容,javascript和其他脚本标记的mish-mesh。只要您定义单独的部分,就可以使用纯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包含两个感兴趣的属性。一系列html内容将被推向&#34;进入动态创建的displayAd div,并使用srcs包含要包含的外部脚本数组。如果您希望在加载脚本后使用脚本(例如DoWork),则需要提供可选的回调。这是一个jsfiddle示例。

有些库可以很好地处理这些(例如requirejs)来加载外部依赖项,但是又想提供一种与库无关的方法。