如何使用Javascript动态地将脚本插入HTML头?

时间:2011-02-27 09:50:22

标签: javascript dynamic

如何使用Javascript动态地将脚本插入HTML头?

3 个答案:

答案 0 :(得分:48)

var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.onload = function() {
    callFunctionFromScript();
}
script.src = 'path/to/your-script.js';
head.appendChild(script);

答案 1 :(得分:2)

#include <iostream>
#include <queue>
#include <string>

struct DATA {
    std::string key;
    int data;
    // EITHER THIS
    bool operator<(const DATA & d2) const {return <your logic here>;}

};
// OR THIS
bool operator<(const DATA &d1, const DATA & d2){return <your logic here>;}


int main() {
    std::priority_queue<DATA> priorityQ;
    DATA newItem;
    newItem.key = "apples";
    newItem.data = 3;
    priorityQ.push(newItem);
    std::cout << priorityQ.top().key << std::endl;

    std::cout << "Press the 'ENTER' key to continue...";
    std::cin.get();

    return 0;
}

答案 2 :(得分:1)

以下是我在没有任何源文件等情况下动态注入函数的方法。

document.head.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}' );

注入身体

document.body.appendChild(document.createElement('script').text = 'function LogIt(msg) { console.log(msg);}' );

执行此操作后,如果您尝试LogIt('hello');,您应该看到&#39; hello&#39;在控制台上。