-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.

19
  • 1
    Uhm... just write it in the header...?! Commented Mar 15, 2014 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. Commented Mar 15, 2014 at 10:40
  • Use echo. Also, be careful about double quoting. Your example doesn't work without escaping those quotes. Commented Mar 15, 2014 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 Commented Mar 15, 2014 at 10:42
  • 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. Commented Mar 15, 2014 at 10:53

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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
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).

Comments

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>

4 Comments

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: 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.
Yeah, I added a comment in the question, anyways thank you for responding.
@user3370402: That's the same as the comment on this thread (unless I'm missing something)?
-1

You may try something like this:

<head>
    <?php echo '<link rel="stylesheet" type="text/css" href="theme.css">'; ?>
</head>

3 Comments

Why the hell two down votes, anyone please explain ?
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!
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.