将脚本属性(数据变量)传递到 head.js

passing in script attributes (data-vars) into head.js?

本文关键字:head js 变量 脚本 属性 数据      更新时间:2023-09-26

有没有办法通过head.js将脚本属性传递到加载的JavaScript中?

例如,我们需要加载的脚本是这样的原始形式:

<script type="text/javascript" charset="utf-8"
src="script.js"
data-vast-src="adscript.js"
data-post-ad-container="content-div"
data-autoplay="true"
data-width="600"
data-height="400">
</script>

所以我们需要的解决方案是这样的:

head.js("jquery.js", { url: "script.js", charset: "utf-8", data-vast-src: "adcript.js", data-post-ad-container: "content-div", data-autoplay: "", data-width: "600", data-height: "400" }, function() {
}

我们已经尝试过这个,但它不起作用...

不,这在 HeadJS 中是不可能的,但您可以自己轻松完成

function addScript(url, attributes) {
    var s = document.createElement("script");   
    s.type = "text/javascript"; 
    s.src  = url;
    for (var item in attributes) {
       s.setAttribute(item, attributes[item]);
    }
    var head = document.head || document.getElementsByTagName("head")[0];
    head.insertBefore(s, head.lastChild);
}
var attributes = {
    "data-vast-src"         : "adscript.js",
    "data-post-ad-container": "content-div",
    "data-autoplay"         : "true",
    "data-width"            : "600",
    "data-height"           : "400"
};
addScript("http://...../script.js", attributes);