最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Does php load BEFORE the 'html body'? - Stack Overflow

programmeradmin1浏览0评论

Difficult to explain this Question, but im currently passing variables in a php page to some html hidden inputs.

Im fetching those values from the hidden inputs with a javascript function. This function gets called like this:

 <body onload="function();">

It works on my system now, but is there any chance that the value passed from php might not get through because body has called the function BEFORE the php code sets the input type hidden?

Thanks

Difficult to explain this Question, but im currently passing variables in a php page to some html hidden inputs.

Im fetching those values from the hidden inputs with a javascript function. This function gets called like this:

 <body onload="function();">

It works on my system now, but is there any chance that the value passed from php might not get through because body has called the function BEFORE the php code sets the input type hidden?

Thanks

Share Improve this question asked Nov 24, 2009 at 19:47 user188962user188962
Add a comment  | 

2 Answers 2

Reset to default 19

You have may have mixed up which part does what.

  • PHP generates the HTML page on the server side. When the HTML page arrives at the browser, PHP has done its job. There is no way for PHP to do something after it has rendered the HTML.

  • Javascript is executed in the user's browser after the page has been generated and loaded. (Or during; as theraccoonbear points out, Javasript can run in the browser before the page has loaded completely.)

  • A Javascript command can not communicate with the PHP script rendering the page, because when Javascript comes into play, PHP is already gone.

So the answer to your question is: No, the JS function can not execute before PHP is done. As several commentators point out, that is not entirely true. A Javascript could come into action before the input HTML elements have been rendered. In your example however, the Javascript triggers only when the document is completely loaded. In that constellation, the answer is no, it can't happen.

That shouldn't be an issue, as you are using the body's onload property, which will ensure the dom and all images etc have loaded.

Using jQuery to it like below would be better in my opinion, fires as soon as the dom is ready, rather than waiting for all images etc.

$(document).ready(function() {
    // do stuff here
});

This is also easily done from an external JS file if required, which helps you logically separate your code.

发布评论

评论列表(0)

  1. 暂无评论