I have the following file file:
<html>
<head>
<title></title>
<script type="text/javascript" src="/Prototype.js"></script>
<script type="text/javascript">
function load_content()
{
new Ajax.PeriodicalUpdater('content', '/UpdatedContent/,
{
method: 'post',
frequency: 5
});
//var fileref = document.createElement("link");
//fileref.setAttribute("rel", "stylesheet");
//fileref.setAttribute("type", "text/css");
//fileref.setAttribute("href", filename);
}
</script>
</head>
<body>
<div id="content"></div>
<script type="text/javascript">
load_content();
</script>
</body>
</html>
Content from UpdatedContent is supposed to be loaded into the "content" div every 5 seconds. What's weird is that the HTML is loaded but the section at the top of the loaded page is completely stripped out when it gets inserted into "content"
The loaded page is essentially this:
<style type="text/css">
... lots of css here ...
</style>
... lots of HTML here ...
There are no , ,
Can CSS not be injected directly into a div?? Is there some reason either the Prototype framework or the browser's DOM is stripping out the CSS?
How can I include the CSS without making a separate call??
As you can see from the given main file, the page would be completely blank without anything loaded in the "content" div. This is intentional. I am basically wanting to use this as a structure on which to dynamically load updating content on an interval, so that the page doesn't have to completely reload to do a refresh of the data.
And no, I can't just hard code the CSS into the above file as the CSS will be changing too.
Edit: Regarding yaauie's response... now I know why it's happening, since I'm passing style and content in one single piece. If I separate the CSS into a separate file that can be loaded, how would I then load this via AJAX (preferrably using Prototype) and then, more importantly, set that CSS as the style sheet for the page content?
The <style> tag is only allowed in the <head> of HTML and XHTML, not the <body> or any of its descendants. Web browsers tend to be fairly forgiving of this in the initial parsing of a document, but when changing innerHTML I would expect that the browser would ignore any <style> elements because that type of element is not expected there.
As a workaround, would it be possible to use inline-CSS in your response, that is use the style="" attribute of the HTML elements you're passing?
EDIT: To add the CSS to the <head> would require one of two things:
Two round trips to your server:
A response that includes both and can be parsed before being inserted
In this case, I would recommend encoding your two parts into a JSON object before sending. Your callback on the AJAX action should split these and attach them to their appropriate locations (style first to avoid screen jitter)
{"style":"\ndiv#ajax7373 a {\n color:#fff;\n text-decoration:underline;\n font-weight:bold;\n \n}\ndiv#ajax7373 {\n background-color:#ff1cae;\n color:#ff6ccf;\n}","object":"\n<div id=\"#ajax7373\">\n\tThere is the contents of your div and a <a href=\"#\">link<\/a>\n<\/div>\n"}
That said, I find it hard to believe that the app favors style/content sepration so strongly and is employing a method where the style must generated by the content. Why not style the whole domain, including the expected return of your AJAX requests? Are the AJAX requested items really going to have enough variance in structure/style to warrant this?
You're stuck with either inline styles for the generated CSS or you'll have to write tons of class names for all the various styles you need so you can still separate out the styling. Then you could alter the class names via JS.
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');
}
});
Ok so I'm fairly new to programming and I'm searching for a solution to the following: I'm trying to update the css of my page on the fly, using JQuery to change the 'href' value in the link tag.
I'm using a simple testcase to try to get it working. I'm using Less for CSS.
I have 2 .less files ('test.less' & 'testTwo.less'). This is my code:
$(function() {
$('#changeButton').click(function() {
$('#style').attr('href', '../testfiles/testTwo.less');
console.log($('#style').attr('href'));
})
})
I log the href value to see if it actually changes, which it does. Only the styling of the page won't change.
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet/less" type="text/less" href="../testfiles/test.less" id="style">
<script type="text/javascript" src="../jquery/jquery.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="changeButton">click me</div>
<script src="../bower_components/less/dist/less.js"></script>
</body>
</html>
I'm definitely missing something here, something I don't know yet about css rendering I suppose. Any help is welcome, thanks! :).
You need to update your code to following
$(function() {
$('#changeButton').click(function() {
$('#style').attr('href', '../testfiles/testTwo.less');
console.log($('#style').attr('href'));
$('style[id^="less:"]').remove(); // you need to remove the less
less.refresh(); // refresh the files
})
})
Notes
It is preferred to have css in html in place of less (performance impact). Use pre compilers at let the html refer to css.
Less compiler does not automatically compile dynamically added files. You need to force less compiler to refresh styles.
You need to remove the less due to the way LESS works. It parses the less file, and then adds a style attribute to the DOM with id attribute as id='less:<<NAME OF YOUR LESS FILE>>'
Whenever we are using less.js all the less file should be loaded before that so that it can compile the less files to css during page load. Since you are adding the less file dynamically it wont get a chance to compile.
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
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});
});
})
Back-story
I am creating a web application in which individual pages are "loaded" via the jQuery .load function. Originally the loaded page was a single file, but as it got longer I decided to split it into a .html file, a .css file, and a .js file.
Strangely, a single design flaw arose surrounding an element that was positioned using percentage values within the css. To see if I modified the styling while I moved, I replace the style tag (omitting the link tag instead) and it worked fine. Back and fourth a few times and I learned it was strictly occurring only when I used link tags rather than embedding it via style tags.
I wanted to use link tags, so I tried to narrow the problem down. After a while of fiddling, I traced it down to the .js file, specifically a usage of the .focus function on $(document).ready. If I comment out the .focus, everything works fine. Uncomment, and it breaks.
This appears to only happen in Chrome. It doesn't occur in FF26 or IE11.
Example
A fiddle.
Note that the problem only occurs in Chrome and that caching must be disabled. As Chrome's temporary cache disable doesn't extend into iframes of iframes, a direct result is easier to work with.
jQuery provides a callback function when the .load() method has completed and the DOM has been updated. This is where you would want to operate on elements that have been inserted from your external url.
<script>
$(document).ready(function() {
$('#content').load('html/portal.html', function() {
//now i can operate on elements loaded from html/portal.html
//they have been inserted into the DOM
$('input#input').focus();
})
});
</script>
As far as references to the link element, if you want to dynamically load a stylesheet from an external url using javascript you can employ a javascript function something like this:
//load deferred stylesheets
function loadStyleSheet(src) {
if (document.createStyleSheet) {
document.createStyleSheet(src);
} else {
$("head").append($("<link rel='stylesheet' href='"+src+"' type='text/css' media='screen' />"));
}
}
If you want to load an external javascript file you can use jQuery.getScript():
jQuery.getScript('/js/external.js');
So putting all of this together, if you want to load some content from an external resource, insert it into the DOM and the load an external stylesheet and an external javascript resource you could do so as follows:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(document).ready(function() {
//function to load a deferred stylesheets
var loadStyleSheet = function(src) {
if (document.createStyleSheet) {
document.createStyleSheet(src);
} else {
$("head").append($("<link rel='stylesheet' href='"+src+"' type='text/css' media='screen' />"));
}
}
$('#someWrapper').load('external-url.html #someWrapper > *', function() {
loadStyleSheet('/css/external.css');
jQuery.getScript('/js/external.js');
})
});
</script>
</head>
<body>
<div id="someWrapper">
<!-- external content is loaded here -->
</div>
</body>
</html>