automatically css/js content in 1 file - javascript

I separate many CSS/JS so it's easier to work in and look over.
But when the website loads, it has to load all those JS and CSS files and that will extend the loading times more and more.
So I was trying to put a simple php script in my website that takes all the CSS content and put it in 1 file. Same goes for the JS content.
It looks like this ($data['js'] and $data['css'] are arrays with all the files):
<?php
$jsData = "";
$cssData = "";
foreach($data['js'] as $js) {
$jsData .= file_get_contents($js);
}
foreach($data['css'] as $css) {
$cssData .= file_get_contents($css);
}
file_put_contents('static/js/javascript.js', $jsData);
file_put_contents('static/css/style.css', $cssData);
?>
<script type="text/javascript" src="static/js/javascript.js"></script>
<link href="static/css/style.css" rel="stylesheet" type="text/css">
As I'm still a beginner I wanted to ask you for tips/suggestions,
What do you guys think?
Thank you

Use this CssJsBundler
The above is on github, and opensource and it does what you have requested !
And also check out http://www.subchild.com/2008/08/07/simple-javascript-and-css-file-bundler/
which tells you how to configure the options.

Related

pass a parameter to my loaded div using jQuery

I have a few html pages that share the same navbar. Therefore I wrote one html file - topnav.html and I used the following jQuery code to load it into every page.
javascript
<script type="text/javascript">
$(function() {
$('#topnav').load('topnav.html');
});
</script>
html
<body>
<div id="topnav"></div>
...
Now, I discovery each page need to have different properties (say different titles). How can I pass the title parameter to the tapnav.html page?
This first solution is in PHP, because I like it much better. If you want to do it in JS, see the edit below.
If you are using PHP, you can include a file (with functions), and pass the function as a parameter, like so:
index.php
<?php
include "topnav.php";
top("title");
?>
topnav.php
<?php
function top($title) {
?>
<div id="topNav">
<!-- Other code you need here -->
<span id="title"><?= $title ?></span> <!-- put in inputted title -->
</div>
<?php
}
?>
I don't use JS/jQuery to load resources (parts of pages) for my websites. PHP include() is much more convenient and I use it all the time!
EDIT
Now that I think about it, you could probably do a very similar thing in JavaScript, although it's slightly more cumbersome. Put a function in the JS, and just call it from the page.
For example:
index.html
<script type="text/javascript">
$(function() {
$('#topnav').load('topnav.html');
$("body").append(top("title"));
});
</script>
topnav.html
<script>
// basically return (or print out) string of resource
function top(title) {
return "<div id='topNav'>" +
"<!-- Other code you need here -->" +
"<span id='title'>" + title + "</span>" +
"</div>";
}
</script>
EDIT 2: More detailed explanation (by request)
What the JS example does is load the resource file like you did in your example. However, instead of it being a plain HTML file like yours, it is a JS file. Once you've loaded it, you now can use the JS script. Basically the added script allows you to use a mostly-predefined string, but you can add some variables (for example, "<span id='title'>" + title + "</span>" allows you to put title into it).

jquery script tag visible in each page

I have included this code using php "include" at the end of the body tag in
</div>
<?php include "jq.php" ?>
</body>
</html>
contents of jq.php----------------------------------------------------------------------------------
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
if (!window.jQuery)
{
document.write('<script src="./script/jquery.min.js"><\/script>');
}
</script>
-----------------but it is visible at the end of each page----------------------------
There's still not much to go on why this isn't working without looking at a lot more of your codebase.
I'd suggest a few things. Firstly, that you probably don't need to include a local copy unless you're doing development work - the chances of Google's CDN being down are very low, and if the user can't access it you'll likely have trouble with other components of the page anyway.
If you do need the local version for development (e.g. if you want to test the site when you're offline) then simply add this to PHP:
if (is_development()){
echo '<script src="./script/jquery.min.js"></script>';
}
else {
echo '<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>';
}
Where is_development() checks some defined CONSTANT or (less ideally) a global variable or local file.
The final approach would be to simply include the jQuery code at the top of your own JS file:
if (!window.jQuery){
var jQuery=.... // full minified jQuery here
}
None of those really answer your query but they should help you continue with your development without too many more problems relating to this issue.

Prepare jquery before jquery and page load

I have recently discovered the new trend of including all .js script at the end of the page.
From what i have read so far seems pretty ok and doable with an exception.
The way I am working is using a template like:
<html>
<head>
<!-- tags, css's -->
</head>
<body>
<!-- header -->
<div id="wrapper">
<?php
include('pages/'.$page.'.php');
?>
</div>
<!-- footer -->
<!-- include all .js -->
</body>
</html>
Now, if I want to use this example on my page http://www.bootply.com/71401 , I would have to add the folowing code under my jquery inclusion.
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
But that would mean I either use that in every page - even if I do not have use for it, either generate it with php in the $page.'php' file and echoing it in the template file, after the js inclusion.
I am sure though, better methods exist and I don't want to start off by using a maybe compromised one.
Thanks!
Please avoid using inline scripts as they are not good maintainable and prevent the browser from caching them. Swap your inline scripts in external files.
Fore example you could put all your JavaScript in one file an check the presence of a specific element before initialize the whole code. E.g.:
$(document).ready(function(){
if($('.thumbnail').length) {
// your thumbnail code
}
});
A better way to execute "page specific" JavaScript is to work with a modular library like requirejs. You can modularize your scripts depending on their functionality (like thumbnails.js, gallery.js etc.) and then load the necessary script(s) depending e.g. on the existence of an element:
if($('.thumbnail').length) {
require(['ThumbnailScript'], function(ThumbnailScript){
ThumbnailScript.init();
});
}
The best way you can go is create a separate file for this code.
Let's name it app.js. Now you can include it under the jQuery inclusion.
<script type="text/javascript" src="app.js"></script>
This will prevent code repeat.
One more thing, pull all the code in $(document).ready(). Here is an example. So your app.js file will look like this:
$(document).ready(function(){
$('.thumbnail').click(function(){
$('.modal-body').empty();
var title = $(this).parent('a').attr("title");
$('.modal-title').html(title);
$($(this).parents('div').html()).appendTo('.modal-body');
$('#myModal').modal({show:true});
});
})

Automatic page reload with jQuery

I have a test page that I keep all my labs on on my local IDE (MAMP). I recently wrote a small php script that will read the directory and create a link of each file in that directory which is help to me as now i don't have to write out the full local url each time to test a new file. I still have to refresh the page though every time i create a new file so its' read. I wanted to set the page to being 'self-reading' so that when i add something, it would appear on the page. I thought Ajax would be a good use of this but the script i tried doesn't work. I've no knowledge of ajax and or jQuery - i'm a super newb honestly - but i'm trying to grow.
My problem in a nut shell: The script does not appear to update the page (maybe it is and i'm not doing it right? I don't know - maybe i ought to be using javascript to refresh the page?)
my code:
<!-- For ease of use, use JQuery hosted lib- you can download any version and link to it locally also -->
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function() {
$("#responsecontainer").load("response.php");
var refreshId = setInterval(function() {
$("#responsecontainer").load('response.php?randval='+ Math.random());
}, 1000);
$.ajaxSetup({ cache: false });
});
</script>
<div id="responsecontainer">
<?php //index.php
$dir_open = opendir('.');
while(false !== ($filename = readdir($dir_open))){
if($filename != "." && $filename != ".."){
$link = "<a href='./$filename' target='_blank'> $filename </a><br />";
echo $link;
}
}
closedir($dir_open);
?>
</div>
<!-- End jQuery auto update div -->

Save HTML as PDF and email using MPDF

I need to be able to send a PDF version of a PHP page's HTML (with CSS styles intact as some tags are set to display: none in a #media print{} clause) as an email.
I found mpdf which looks relatively easy and seems like a solid solution. The class offers the ability to email a PDF file on the fly. This is great.
My dilemma is as follows:
I want to send page_1.php's contents to send_email.php as a url variable to use as the PDF content.
To store this variable I have tried:
ob_start(); // at the top of the page
// THE DYNAMICALLY GENERATED PAGE CONTENT
$html = ob_get_contents(); // I put the page contents into a variable
ob_end_clean();
For some reason this does not let the page load in it's entirety. Only a few tags show up. The ob_get_contents(); and ob_end_clean(); are sitting before the end </html> tag. Is this a potential cause?
I need to use these functions before the end of the page to utilize the variable higher up at the actual 'email link' I created.
I have also tried:
$page_url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; // to grab the current url
$html = file_get_contents($page_url); // place contents in a variable
For some reason, this does not allow any page on the site to load. All one gets is a spinning wheel in the browser url input.
Even if I can get the page's content into a variable and parse it to send_email.php, how would I retain the CSS properties when creating the PDF?
Would a javascript alternative be more viable?
Any help would be outstanding!
I've had success posting the html to the php file:
$html = $_POST['html'];
$head.= '<link rel="stylesheet" type="text/css" href="/app/css/app.css" /> ';
$head.= '<link rel="stylesheet" type="text/css" href="/app/css/pdf_style.css" /> ';
require_once 'mpdf/mpdf.php';
$mpdf = new mPDF('', 'Letter', 0, '', 12.7, 12.7, 12.7, 12.7, 0, 0);
$mpdf->WriteHTML($head.$html,0);

Categories

Resources