-4

Lets say I have markup like:

<!DOCTYPE html>
  <html>
    <head>
    </head>
  <body>
     <?php
     PutIntoHeader("<script src="im_on_top"></script>")
     ?>
  </body>
</html>

The PutIntoHeader function would put the given script into the head section of the html which is rendered. I might be missing something really obvious, but I cant seem to figure that out. Any ideas how the function would be able to do that?

The output would be:

<!DOCTYPE html>
  <html>
    <head>
       <script src="im_on_top"></script>
    </head>
  <body>
  </body>
</html>

Thank you for any ideas.

Edit:->

Hi, I feel like a noobie getting this kind of answer:) My system is highly complex and in the time I write header I dont know which scripts will get requested for that particular page as its all dynamic. I could put all html in variable before it gets rendered and then traverse it as xml and put it there manually while storing the scripts in an array but I dont want to go this road.

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
  • 1
    Uhm... just write it in the header...?! – deceze Mar 15 '14 at 10:40
  • This is very simplified example, I cannot write it in header in the real world scenario as I dont know at that time which scripts will get eventually loaded. – user3370402 Mar 15 '14 at 10:40
  • Use `echo`. Also, be careful about double quoting. Your example doesn't work without escaping those quotes. – domdomcodecode Mar 15 '14 at 10:41
  • Are you building a cms? If so you can create a function that can get the header from current file and append that script – Jorge Y. C. Rodriguez Mar 15 '14 at 10:42
  • Actually yes, this is about CMS and the content is all dynamic so the suggestion here just makes me look like newbie without really thinking about the issue..Could you a little more elaborate on what you mean? – user3370402 Mar 15 '14 at 10:46
  • Then figure out what scripts you need to include *before* the header. – deceze Mar 15 '14 at 10:48
  • Well, thats the point of whole this issue - I cant. Say that the page consists widgets and each widget in order to work needs to have some additional css/scripts in the header(goes for CSS, I can put the js in the bottom, but that is not the point). – user3370402 Mar 15 '14 at 10:51
  • 1
    You need some sort of dependancy checking for your widgets. Store a list of dependencies each widget needs. When you goto load the page figure out what widgets you are going to include before you get to outputting the head. – Jon Taylor Mar 15 '14 at 10:53
  • Or include the scripts at the bottom of your body? – Jon Taylor Mar 15 '14 at 10:54
  • That is what I used in the past.. However the problem with this is that I have store it separated from the actual php markup, maybe I will do this again, but I do work with .NET where this is so easily possible I thought the php could have something similar.. – user3370402 Mar 15 '14 at 10:55
  • Why on earth do you need to include different scripts on different pages. In almost all situations you simply want to combine and minify all scripts and just always include it. – PeeHaa Mar 15 '14 at 10:57
  • Well, this is not one of those cases because that way I would have to include hundreds to thousands of scripts... – user3370402 Mar 15 '14 at 10:58
  • @PeeHaa really? I have never, and would never do this. – Jon Taylor Mar 15 '14 at 10:59
  • "hundreds to thousands" no you would not. Nobody needs to do that, ever. – PeeHaa Mar 15 '14 at 10:59
  • @PeeHaa if it is a widget based system where script includes could be dynamic based on a widget per widget basis, then yes it could very well need that. – Jon Taylor Mar 15 '14 at 11:01
  • If you think you need to include thousands or even hundreds of script you are doing something terribly wrong and it is utterly fubar. – PeeHaa Mar 15 '14 at 11:02
  • @PeeHaa Have you ever seen some modular system which contains more then 10 widgets? In my case you can have million widgets if users want so I really dont want to include them all, even if its only a thousand and not million. Anyways this really doesnt solve it :/ – user3370402 Mar 15 '14 at 11:05
  • Not at all, how about you have a base dashboard which can have any of several thousand widgets, they all use different dependencies or combinations of dependencies. Why on earth would you ever program it to always include every dependency for every widget regardless of if you will need it or not. To me this would be incredible lazy and bad programming. – Jon Taylor Mar 15 '14 at 11:06
  • So you have a million widgets and all of those million widgets have their own specific code (not talking about data here, but code)? If yes then yes you are in the situation I wrote about when saying "In **almost** all situations you" – PeeHaa Mar 15 '14 at 11:07

4 Answers4

2

If you don't want to put it directly in the head because at the time you don't know what's going to be needed, you need to carry out the logic beforehand.

You need to separate the logic from the view and have the view as a simple way of rendering your information.

First calculate everything about your page and leave yourself with variables which you can use to extract relevant information, then output the relevant html for the variables you have calculated beforehand.

This could be done yourself in one page, or what I would suggest, is using some sort of library to help out with this. Something like Kohana is really good at this, you could use Kohana to separate out your controllers, models etc and then use something like mustache as a templating library. Mustache lets you create views with only the most basic of logic in them (the way it should be).

Jon Taylor
  • 7,865
  • 5
  • 30
  • 55
2

In almost all situations you can simply get away with combining and minifying you scripts into a single file. This slows down the initial loading time (first visit of site), but will speed up further visits / navigation because the file will be cached.

Of course YMMV and it depends on your specific situation. See for example this thread.

There is also the thing that user agents cannot do unlimited concurrent connections to the same domain to load resources.

See for example these two (somewhat outdated) benchmarks:

In the comments you said you are working with a million different widgets. Does this mean that these widgets all have completely specific and different code or is just the data different or presented differently? If it is just data / presentation you don't need different script for that.

If indeed you are talking about a million completely different codes for the different widgets (a million suddenly sounds like a made up arbitrary number) it indeed may make sense to not load everything in a single script. But this is impossible to answer by us, because it depends on the filesize, how fast you want to load the first visit, how many shared code it has and more numbers like that.

So to get back to your questions "How can I load specific scripts in the head?".

One option would be to not render it in the head, but place it just before the </body> and body tag instead. The advantage of this approach is that you know what script to load by then. The pages will load faster (because resources in the head will be first downloaded in full before the actual page is ever going to be rendered). The drawback of this approach is that there is a small latency before your script will kick in because it will be last thing that gets loaded in the DOM.

Another option would be to defer the rendering of you HTML on the PHP side and using it more like a templating engine. A simple example of this is by first getting all the widgets you want to display and only after you have done this start the HTML rendering in PHP.

some bootstrap file

<?php

// load widgets from db or wherever
$widgets = [
    [
        'template' => '/templates/widget1.phtml',
        'script'   => '/js/widget1.js',
    ],
    [
        'template' => '/templates/widget2.phtml',
        'script'   => '/js/widget2.js',
    ],
];

require __DIR__ . '/templates/page.html';

some template (page.phtml)

<!DOCTYPE html>
<html>
    <head>
        <title>My page with widgets</title>
        <?php foreach ($widgets) { ?>
            <script src="<?php echo $widgets['script']; ?>"></script>
        <?php } ?>
    </head>
    <body>
        <?php foreach ($widgets) { ?>
            <?php echo $widgets['template']; ?>
        <?php } ?>
    </body>
</html>

P.S. in the above example I have used script tags, but it could also be expanded for css files also obviously.

Community
  • 1
  • 1
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
  • I will accept your question as you are correct with this approach. Also note that I mentioned the possibility of loading js before end body tag, but that would not work with css so good. However the widgets were just to ilustrate the issue, Im not using widgets at all. I was merely curious of if there is some way like it is e.g. on .NET to have method which you can call everywhere, anytime and it will eventually get inserted in Header. As I said, this can be done with storing all output html in variable and then accesing the head section and inserting those scripts before rendering final html – user3370402 Mar 17 '14 at 10:07
1

Your PHP code has no way to know where the contents should be output. PHP loses its control over the data once the page is rendered.

You seem to be trying to write the content in the <body> and then have it injected in <head> section. Why don't you output the content in the <head> section instead?

<!DOCTYPE html>
  <html>
    <head>
        <?php echo "<script src=\"im_on_top\"></script>"; ?>
    </head>
  <body>    
      <!-- Some HTML markup here -->
  </body>
</html>
Amal Murali
  • 75,622
  • 18
  • 128
  • 150
  • Hi, I feel like a noobie getting this kind of answer:) My system is highly complex and in the time I write header I dont know which scripts will get requested for that particular page as its all dynamic. I could put all html in variable before it gets rendered and then traverse it as xml and put it there manually while storing the scripts in an array but I dont want to go this road.. – user3370402 Mar 15 '14 at 10:44
  • @user3370402: I'm sorry if you got that impression. I suggest you edit your question to make it pefectly clear what you're trying to achieve. In its current form, it appears that you're trying to change the structure of the web page *after* the page has finished loading. – Amal Murali Mar 15 '14 at 10:46
  • Yeah, I added a comment in the question, anyways thank you for responding. – user3370402 Mar 15 '14 at 10:48
  • @user3370402: That's the same as the comment on this thread (unless I'm missing something)? – Amal Murali Mar 15 '14 at 10:49
-1

You may try something like this:

<head>
    <?php echo '<link rel="stylesheet" type="text/css" href="theme.css">'; ?>
</head>
The Alpha
  • 143,660
  • 29
  • 287
  • 307
  • Why the hell two down votes, anyone please explain ? – The Alpha Mar 15 '14 at 10:52
  • 2
    They think that you should read the answers and comments posted 10 mins after you posted this answer! Your answer is perfectly valid with the information you had at the time! – misterManSam Mar 15 '14 at 11:02
  • 1
    I downvoted another answer for the same when they answered clearly without having read any of the previous comments, but I upvoted this answer from the start. – Jon Taylor Mar 15 '14 at 11:14