This is a common bug in front-end page development, and it’s not the first time I’ve encountered it. But since I don’t often write front-end code, I have to remember the reason and the solution every time I encounter it again, so write it down in case I encounter it again.
Bug back
The project USES an Ext component, requiring an image to be displayed on the page and the image address passed in as a parameter from the previous page. My simple idea is to create a new Pannel and write an HTML code block inside it. The code block looks like this
"<img id='qrImage' src='com/system/empty.bmp' width='100%' height='100%'>"
The initial address of the image is a temporary image. When we get the image address we need to display, we will use the DOM of the operation page to set it to the new address. The address length is set as follows:
document.getElementById("qrImage").src = filePath;
It looks like there is no problem, but when the page loads, an error is reported. The error is in the above statement, and the error message is:
Uncaught TypeError: Cannot set property 'src' of null
solution
Not often write the front end suddenly scared, my first reaction turned out to be that there was something wrong with the method to get ID, such as misspelling of letter case and so on. After all, she was a careless girl. However, the harsh reality is that the W3C told me there was nothing wrong with the approach.
since not get property method no problem (actually it can’t be a method name write wrong, or the browser will report is not a function), it must be written the dom itself has a problem. The most intuitive way is of course debug, bug is also relatively simple, follow up to find the problem.
why
“Document.getelementbyid (” qrImage”) “here, the code does not get an element whose Id is” qrImage “, so it is null. Null does not have a set attribute, so the browser will throw this error:
Uncaught TypeError: Cannot set property 'src' of null
Then the rendering of the page will stop and the page will report an error.
The solution
The solution is to make sure that the element qrImage is rendered and available to the browser before the properties are set, so that no errors are reported. My project actually USES the Ext component and USES ExtBuilder to simplify development (in case my writing doesn’t work in other situations) by replacing the code with:
var infoPanel = Ext.getCmp("saveQR");
infoPanel.html = "<img id='qrImage' src=\"" + url+ "\" width='100%' height='100%'>";
The problem can be solved.
tips
For those who are not using Ext or Ext development components, you can use window.load or AfterRender methods to make sure that the page is loaded before you do anything with it.