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});
});
})
Related
I am trying to load an external HTML page (common navigation) into my current HTML page. I tried the load function but it is deprecated. Can you tell me another way to include it? I am not using any server.
Here's my code
<!DOCTYPE html>
<html>
<head>
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#content').load(" nav.html ");
});
</script>
</head>
<body>
<div id="content "></div>
</body>
</html>
Try this
<script>
function loadPage(href) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", href, false);
xmlhttp.send();
return xmlhttp.responseText;
};
document.getElementById('content').innerHTML =
loadPage('your_html_file.html');
</script>
<div id="content">
</div>
Take both file pages in same directory then you can use simple button on link to use external file. for example
<button> External file </button>
Button is your choice it's just example for understanding you can simple use html link.
You should use the SSI-function.
There is several ways but this can solve your problem.
<!--#include virtual="PathToYourFile/YourFile.html" -->
This can be inserted into a <div> for further styling in CSS.
REMEMBER! Due to some limitations in html-doctypes you cannot inlude a .html-file into an .html-file. You have to use another format as .shtml where you can inlude your .html-files. You can include .html into your .shtmlfile. This was also what .shtml was originally created for.
This is because it is part of the XHTML (Dynamic XML HTML)...
To change a file
Your approach on the HTML is correct and also your JS. I include a lot of html-files containing texts there.
My approach is that when a page is loaded some text will be loaded with the <!--#include virtual="" --> inside a <div>. Below JS is used to change the content in the <div>. As Daniel Beck stated below: "...at least in Apache the server needs to be configured to check particular file extensions...".
You configure your file in your .htaccess-file. But ONLY do this if you know what you are doing.
Some (newer?) servers have a default setup of which you don't need to alter the .htaccess-file if you want to be able to include .html-files. At least you are able to include .html-files into .shtml-files.
I have included a Mimetype converter which tells the browser how it should read the file. For txt/html I have told the script that it should use the character encoding ISO-8859-1. Others as UTF-8 could also be used. This depends on your and your receivers native language.
Take into consideration to use the e.preventDefault();. With this i tells the browser NOT to see this as navigation link and will therefore only load the content in the <div>.
$(function() {
$('#ButtonsID').click(function(e) {
$('.DivClass').load('PathToFile/File.shtml');
e.preventDefault();
});
});
$.ajaxSetup({
'beforeSend': function(xhr) {
xhr.overrideMimeType('text/html; charset=ISO-8859-1');
}
});
I have a layout file where i included Jquery just before closing tag.
//layout.handlebars
<!DOCTYPE html>
<html>
<head></head>
<body>
{{{body}}} // renders the body content
<script src='/js/jquery-2.2.4.min.js'></script>
</body>
</html>
I also have a page specific javascript(helper.js) that makes an Ajax call.
<div>Some sample data</div>
<script src="/js/helper.js"></script>
but the problem here is jquery is loaded at the end of the page but i am referring to it in the external javascript before jquery is loaded. which shows me '$' is not defined and i know that is obvious.
One solution to this will be like adding jquery to the head section but that is not what i want.
Is there any approach that i can apply to make an ajax call from external file without moving Jquery to head section.
Any help is much appreciated!!
Is there any approach that i can apply to make an ajax call from external file without moving Jquery to head section.
Yes, I assume you already understand the cause of the issue. As you see below the final content is ..
<!DOCTYPE html>
<html>
<head></head>
<body>
<div>Some sample data</div>
<script src="/js/helper.js"></script> <!--Jquery is not loaded yet, and hence $ is undefined -->
<script src='/js/jquery-2.2.4.min.js'></script>
</body>
</html>
As you already know one option is to move jquery anywhere in the HTML but make sure its loaded before any other jquery dependent files. Now since you don't want to take this option. we have another option.
Solution:
Our only aim is to make sure the jquery library is loaded prior to any other jquery dependent files.
We can get the files on document.ready using $.getScript()
$(function(){
$.getScript( "/js/helper.js", function( data, textStatus, jqxhr ) {
console.log( "Load was performed." );
});
});
Extras: If you feel this is a overhead and you cannot add this code to all the files in your page (since there can be too many files ), You can write a generic function and a global array variable , This function will check for file paths in the array and execute each one synchronously and remove from the array. Make sure this generic function is called in every document.ready event.
One Solution is that You can put the jquery script at the start of body tag before {{{body}}} section .. In this way your helper script will be rendered after jquery and your problem will be solved .....
Well its not pretty but you could use some kind of test and wait loop something like
<script>
(function test(){
if( window.jQuery ){
//your jQuery code
} else {
setTimeout(function(){ test(); }, 200);
}
})
</script>
I am relatively new so I may not have done them right but I have tried them. The closest I got is the code I am including. It was work for awhile but the modals wouldn't "fire". I tried to remedy that and lost my inclusion. So here goes.
HTML
<!--============================================-->
<!-- End of Main Program, Modals Follow -->
<!--============================================-->
<section id="activeModal">
<!--> placeholder for every modal in this project </!-->
<!--> each modal is stored in a separate file (modals.html) </!-->
<!--> main.js builds an include with a js script, appends it here, and it executes (hopefully) </!-->
</section><!-- /activeModal -->
JS
// event listener for modals
$("button").on('click', function() {
for ( i=0; i<this.attributes.length ;i++ ) { // this - identifies the modal sought
if ( this.attributes[i].name === "data-target" ) {
var target = this.attributes[i].value; // get the modal to "fire" (data-target attribute)
};
};
modalId = "modals/"+target.substring(1, target.length)+".html"; // strip the '#' from target
$("#activeModal").empty(); // remove any previous modal information
includeHTML = '<!--#include virtual="'+modalId+'" -->'; // include via ssi (server side include)
$("#activeModal").append(includeHTML); // append the 'import' html
$(target).modal("show"); // show the modal
});
I am expecting the html for any of about 20 modals to appear in the activeModal <section> of index.html. Then, I have the problem of making them "fire".
Based on this line, it looks like you are trying to use server-side includes on the client-side when a button is clicked.
includeHTML = '<!--#include virtual="'+modalId+'" -->'; // include via ssi (server side include)
This is quite simply impossible.
You can't trigger a server-side include with client-side code. Server-side includes must be made before the response is sent to the client. To get more data from the server, you will have to initiate another request, perhaps via AJAX.
var stackoverflowResponse = document.createElement("div");
stackoverflowResponse.innerHTML = "Look in the console for the answear";
document.body.replacewith(stackoverflowResponse);
You could try changing the extension of your index.html to .shtml, and then using Server Side Includes to include the content of another file.
<!--#include file="included.html" -->
When I did this, I also believe I had to update the .htaccess file to recognize the .shtml as an index file:
AddType text/html .shtml
AddHandler server-parsed .shtml
AddHandler server-parsed .shtml .html
AddHandler server-parsed .shtml .htm
Well you can try out something like this using jquery:
<html>
<head>
<script src="jquery.js"></script>
<script>
$(function(){
$("#includedContent").load("xyz.html");
});
</script>
</head>
<body>
<div id="includedContent"></div>
</body>
</html>
This is a question from a noob in javascript. I tried to find something similar the last two days but I didn't find. I try to pass an html image element to an external javascript file which I include to the rest html code. The javascript fade in and fade out an image. Because I want to use different images everytime, thus I want to have a function in an external javascript file.
What I did so far:
PHP and HTML:
<?php
if ($success){
echo"<link rel='stylesheet' href='js/jquery-ui-1.11.4-smoothness.css'>
<script src='js/jquery-1.11.3.js'></script>
<script src='js/jquery-ui-1.11.4.js'></script>
<img id='tick' src='tick.png'>
<script type='text/javascript' src='js/success_failure_signs.js'>
success_failure(tick);
</script>";
}?>
Javascript file has this code:
function success_failure(tick){
var x = tick;
x.fadeIn();
x.fadeOut(1000);
}
The browser's console doesn't give any error.
It seems that the function success_failure doesn't get the image.
What is wrong on this code and how can I fix it?
Thank you in advance!
You haven't defined tick when you make your function call. Try this...
<script type="text/javascript" src="js/success_failure_signs.js">
</script>
<script type="text/javascript">
var tick = $("#tick");
success_failure(tick);
</script>
EDIT: I've also separated the inclusion of the script and your code to call it into two separate script tags.
maybe passing the image to the script is the wrong way of thinking here.
Most of the time with Javascript for web pages the JS gets the image from the HTML site itself.
You are already including jQuery so look into how to get an element from the page with jQuery.
As my website has only one page, and the index.html was getting really long and impossible to read. So I decided to put each section in a different HTML file and use jQuery to included it.
I used jQuery's include in the way as it has been mentioned here to include a external HTML file but apparently it doesn't work for my website. I really don't know what is the problem.
Here is the link of my workspace.
Here is what I am doing in index.html file to include other sections
<script src="./js/jquery-1.11.1.min"></script>
<script>
$(function() {
$("#includedContent").load("./page1.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page2.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page3.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page4.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page5.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page6.html");
});
</script>
<script>
$(function() {
$("#includedContent").load("./page7.html");
});
</script>
I also used this method to make sure the file is accessible and everything was fine. So the problem is not the accessibility of the files
You are overwriting the contents of #includedContent seven times (see documentation of jQuery.load). With AJAX, there is no guarantee which request will complete first so you will end up with random page content inside the container.
The solution is to create containers for each page and load each page inside its dedicated container, something like this:
<div id="includedContent">
<div class="page1"></div>
<div class="page2"></div>
<div class="page3"></div>
</div>
$(document).ready(function() {
$("#includedContent .page1").load("page1.html");
$("#includedContent .page2").load("page2.html");
$("#includedContent .page3").load("page3.html");
});
NB: Having said all that, I do not understand how AJAX solves the problem of the page being too long/impossible to read.
There are several things that look odd to me:
all your load functions run at document ready, which is weird while having all the same target. load replaces (not adds) the content of the selected element with what is being loaded, you probably are trying to add all the html contents, but your current setup would actually just load page7.html into #includedContent
the paths look strange to me, i guess ./ may cause errors, try to leave out ./ everywhere.
rather than loading an entire html page, you might just want to load a piece of that file (i dont know how pageX.html looks), for example you would not want to load the <html> node entirely, rather the content only: .load('page1.html #content')
are you including jquery correctly? there is no .js in your inclusion