脚本在页面加载之前执行

Script executing before page load

本文关键字:执行 加载 脚本      更新时间:2023-09-26

我已经完成了一个脚本,该脚本在包含电子邮件所在的文本区域的页面上运行。

我正在此页面上做各种事情,但是其中之一是根据选定的数字加载iframe,然后在iframe加载后从此页面获取我需要的相关详细信息。

我已经在一个名为frameLoaded的函数中编写了代码,并将其设置为onload事件,但脚本仍然遇到找不到元素的.innerHTML的错误。

如果我加载 iframe 然后执行此脚本,它可以正常工作,但是如果我尝试加载 iframe 并一起执行脚本,则会遇到此错误。

这是我使用的代码:

//Getting text currently in the textarea
var selectedTxt = document.getElementById('txtEmailText').value;
//Converting it to a string - this is just for troubleshooting purposes that I've used two variables
var insertText = selectedTxt.toString();
//Loads in the highlighted purchase number
var purchaseNumber = window.getSelection();
purchaseNumber = purchaseNumber.toString();
//Declares global variables to hold the title and number
var purchaseTitle;
var purchaseNumber;
//Function to execute code to grab title and number once the frame has loaded
function frameLoaded() {
var iframe = document.getElementById('purchaseIframe');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
          purchaseTitle = innerDoc.getElementById('listingTitle');
          purchaseNumber = innerDoc.getElementById('auctionSoldIdDisplay');
         }  

//Checks to see if a purchase number has been selected 
if(purchaseNumber.length > 0){
var purchaseIframe = document.createElement('iframe');
purchaseIframe.src = 'http://www.mysite.co.nz/Admin/Listing/PurchaseDisplay.aspx?asid=' + purchaseNumber + '&submit1=++GO++';
purchaseIframe.setAttribute("height","1000");
purchaseIframe.setAttribute("width","100%");
purchaseIframe.setAttribute("id","purchaseIframe");
purchaseIframe.setAttribute("onload", "frameLoaded();");
void(document.body.appendChild(purchaseIframe)); 
}
//Converting the value in the title to readable text
purchaseTitle = purchaseTitle.innerHTML;
//Placing the values in to the format I need
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
//Placing the values in to the string to go back in to the email textarea
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
//Pasting the variable in to the textarea
document.getElementById('txtEmailText').value = insertText;

我在这里做错了什么还是使用了错误的事件,因为在我看来,它可能试图在 iframe 完全加载之前抓取值,因此当我同时生成 iframe 时出错。

请注意,我不能使用 JQuery

window.onload = function() 是你的答案。

请注意,在下面的示例中,document.getElementById('mydiv')的第一个实例返回null,因为页面(DOM)尚未加载,因此div也没有加载。

第二个实例在 windows.onload 上触发,这意味着所有页面内容都存在,因此可以找到。

<script type='text/javascript'>
console.log("Page not ready:" + document.getElementById('mydiv'));
window.onload = function() {
  console.log("Page ready:" + document.getElementById('mydiv'));
}
</script>
<div id="mydiv">
</div>