jQuery loading data to page before css is loaded? - javascript

I'm a complete newb in nodeJS, javascript and CSS. I'm currently writing a single-page application. I've added to my client side
a javascript file that contains several functions that retrieve data from the server.
In the head section of the HTML, I first load the css files and then the js file like so
<head>
...
<link rel="stylesheet" href="...">
<link rel="stylesheet" href="...">
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
<!-- ajax functions script -->
<script src="js/ajaxFunctions.js"></script>
</head>
Then, in my html, at some point, I call one of the functions in the ajaxFunctions.js like so:
<script type="text/javascript">populatePostsList()</script>
Now, the function works and retrieves the data but for some reason, when working in chrome (and chrome canary) the information is presented without the CSS styling. I have no idea why this is happening. Also, when I check it in safari it actually does work but 10% of the time, it goes back to regular html with no styling.
Has anyone ever encountered this kind of problem and can direct me in the right way?
Also, is this the best way to go about using ajax? How can I implement it so I won't
have to call the actual function but it will get called automatically when the page is first loaded?
Thanks!
I'm adding here a snippet of the populatePostsList() function.
function populatePostsList() {
var counter = 1;
$(document).ready(function() {
$.get(URLAddress + '/getPosts', {} ,function(data) {
var arr = data;
for(var i = arr.Posts.length - 1 ; i >= 0 ; i--) {
var post = arr.Posts[i];
$('#newPosts').append(// appending fields from post // );
});
});
}

Related

How to Dynamically Load Javascript File into HTML

I'm a bit confused on what's required to dynamically load a JS file into the DOM.
When I include in my HTML file, example.js will run normally.
When I include it will add to the DOM but not run it.
I previously believed that I had to recreate , then append() it to the tag. I feel as if I am missing a crucial step, I just don't know what that step is.
example.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="example.js"></script><!-- working -->
<script src="add-example-dynamically.js"></script><!-- not working -->
</head>
<body>
<script>
execute( anyScriptElement ); // not working
</script>
</body>
</html>
</body>
</html>
add-example-dynamically.js
function toExecutable( tagElement ){
// Duplicate the provided tag as a new element in order for all tags to run the 'src' attribute after adding it to the DOM
// Required to run: <script src=""></script>
var newTag = document.createElement( tagElement.tagName );
if( tagElement.hasAttributes() ){
// Check if the tag has attributes
for( var countAttributes = 0; countAttributes < tagElement.attributes.length; ++countAttributes ){
var name = tagElement.attributes[ countAttributes ].name;
var value = tagElement.attributes[ countAttributes ].value;
newTag.setAttribute( name, value );
}
}
if( tagElement.textContent ){
// Check if the tag has content within it
newTag.textContent = tagElement.textContent;
}
return newTag;
}
function execute( anyScriptElement ){
var tag = toExecutable( anyScriptElement );
document.getElementsByTagName( 'head' )[ 0 ].append( tag );
}
var theScript = document.createElement( 'script' );
theScript.src = 'example.js';
execute( theScript ); // not working
Things I've tried (or a variation of)
error loading javascript files dynamically
I've also been adding .onload and .onreadystatechange to various objects without success.
Things I don't quite yet understand
Dynamically load a JavaScript file
How do you import multiple javascript files in HTML index file without the bloat?
Dynamically load a JavaScript file
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
https://cleverbeagle.com/blog/articles/tutorial-how-to-load-third-party-scripts-dynamically-in-javascript
https://humanwhocodes.com/blog/2009/07/28/the-best-way-to-load-external-javascript/
Things I don't think solve my problem
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
https://gomakethings.com/a-better-way-to-load-scripts-with-javascript-or-why-document-write-sucks/
Thoughts
I have a feeling that the right solution doesn't involve XMLHttpRequest or Promises but I'm not certain.
My repository in question: Widgets
If someone could point me in the right direction, that would help me figure out what I need to look into.
FYI
Native JS ideal, not interested in JQuery.
I only care about support for Chrome, Firefox, Opera, Safari (desktop / mobile)
So I found the issue was with the order that I was resolving code. It took forever to find because there was nothing inherently wrong with my code, but the sequence was wrong.
I was calling everything in the correct order, but the order that things were resolving in my network panel were incorrect.
Once I fixed the sequence that things were being loaded into the DOM, everything worked as expected.
Fix #1
Because my XMLHttpReqests should be asynchronous, I put all the calls into a single Javascript file so they would run synchronously.
I needed Javascript files to be loaded in the tag before loading function calls that reference those files.
The function calls I wrapped in window.onload = function(){}.
Basically my final solution was for any <script>code</script> that I was dynamically placing in example.html I would wrap in window.onload = function(){}.
i.e. <script>window.onload = function(){ code }</script>
Fix #2
I was using the onload wrapper window.onload = function(){} in a location that did not make sense. Also it may have been nested within another window.onload function at one point while debugging, which probably didn't help.

How to load a CSS dynamically in cordova

I'm trying to load a CSS dynamically in cordova over a xhr request.
The loading of the CSS is not a Problem, I can load it over xhr and store it to the filesystem over the HTML5 File API. Then I can get a URL this works perfectly.
But if i create a new link element in the header by javascript, like this:
<link rel="stylesheet" type="text/css" id="skin" href="cdvfile://localhost/temporary/mydomin.tdl/skin.css">
Thy stylesheet don't have any effect, how can I force cordova to take the stylesheet in account?
* UPDATE: I've got a working solution and I'll add it to my answer below *
I've found this problem and the suggested answers unfortunately haven't resolved it.
Loading the CSS data from an external PHP script via an XHR request (as my CSS data is dynamic to each page) I use:
var storeCSSURL = "https://www.example.com/dynamicCSS.php?storeID=x";
$('head').append('<link rel="stylesheet" href="' + storeCSSURL + '" type="text/css" />');
I'd also tried replacing the existing stylesheet link with the new URL; and added datetime stamp to it to prevent caching, which also didn't work.
Works great in the web browser and I know the data is loading through the XHR request and also being applied to the head CSS tag, although it doesn't work in Cordova / Phone Gap... the Apps just don't update with the CSS changes from the PHP script.
* NEW UPDATE *
I finally came up with a solution that works, it's a bit of a hack as it doesn't directly solve the problem; but works around it and is great for my needs.
In PhoneGap / Cordova, I use a pageInit.js type scenario that loads the web page in dynamically from a PHP script, I imagine most people use it in a somewhat similar way.
After page load I added:
$("body").append('<style id="dynamicStyles"></style>');
Then simply did a $.POST request to the Dynamic CSS (PHP) file, which returned all the dynamic style data; which I then loaded into a style tag.
This looks something like this:
$.post("https://www.example.com/controller.php", { url: url }, function (data, status) {
if (status == "success") {
$("body").html(data);
// Loads the main page content into the body tag
$("body").append('<style id="dynamicStyles"></style>');
// Appends the main page content with a style tag
$.post("https://www.example.com/dynamicCSS.php", { storeID: storeID }, function (data, status) {
if (status == "success") {
$("#dynamicStyles").html(data);
// Loads CSS data from external PHP script dynamically
// then places it into the new style tag.
}
});
}
});
The CSS updates from this line:
$("#dynamicStyles").html(data);
This loads all the new dynamic style data into the style tag; so the result is an on-page style definition, which you can replace the styles with using .html() at any stage from your external PHP with CSS data.
Phone Gap / Cordava recognises the style tag changes and updates visuals accordingly :-)
I'm sure you could set your project up to load all CSS data in this way instead of the normal head CSS link; and you'd never have that annoying CSS caching issue with Phone Gap / Cordova.
I hope this is useful to someone!
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
$(document).ready(function () {
$("a").click(function () {
$('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
});
});

How do I hide javascript code in a webpage?

Is it possible to hide the Javascript code from the html of a webpage, when the source code is viewed through the browsers View Source feature?
I know it is possible to obfuscate the code, but I would prefer it being hidden from the view source feature.
I'm not sure anyone else actually addressed your question directly which is code being viewed from the browser's View Source command.
As other have said, there is no way to protect JavaScript intended to run in a browser from a determined viewer. If the browser can run it, then any determined person can view/run it also.
But, if you put your JavaScript in an external JavaScript file that is included with:
<script type="text/javascript" src="http://mydomain.example/xxxx.js"></script>
tags, then the JavaScript code won't be immediately visible with the View Source command - only the script tag itself will be visible that way. That doesn't mean that someone can't just load that external JavaScript file to see it, but you did ask how to keep it out of the browser's View Source command and this will do it.
If you wanted to really make it more work to view the source, you would do all of the following:
Put it in an external .js file.
Obfuscate the file so that most native variable names are replaced with short versions, so that all unneeded whitespace is removed, so it can't be read without further processing, etc...
Dynamically include the .js file by programmatically adding script tags (like Google Analytics does). This will make it even more difficult to get to the source code from the View Source command as there will be no easy link to click on there.
Put as much interesting logic that you want to protect on the server that you retrieve via AJAX calls rather than do local processing.
With all that said, I think you should focus on performance, reliability and making your app great. If you absolutely have to protect some algorithm, put it on the server, but other than that, compete on being the best at what you do, not by having secrets. That's ultimately how success works on the web anyway.
No, it isn't possible.
If you don't give it to the browser, then the browser doesn't have it.
If you do, then it (or an easily followed reference to it) forms part of the source.
My solution is inspired from the last comment. This is the code of invisible.html
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="invisible_debut.js" ></script>
<body>
</body>
The clear code of invisible_debut.js is:
$(document).ready(function () {
var ga = document.createElement("script"); //ga is to remember Google Analytics ;-)
ga.type = 'text/javascript';
ga.src = 'invisible.js';
ga.id = 'invisible';
document.body.appendChild(ga);
$('#invisible').remove();});
Notice that at the end I'm removing the created script.
invisible.js is:
$(document).ready(function(){
alert('try to find in the source the js script which did this alert!');
document.write('It disappeared, my dear!');});
invisible.js doesn't appear in the console, because it has been removed and never in the source code because created by javascript.
Concerning invisible_debut.js, I obfuscated it, which means that it is very complicated to find the url of invisible.js. Not perfect, but enought hard for a normal hacker.
Use Html Encrypter The part of the Head which has
<link rel="stylesheet" href="styles/css.css" type="text/css" media="screen" />
<script type="text/javascript" src="script/js.js" language="javascript"></script>
copy and paste it to HTML Encrypter and the Result will goes like this
and paste it the location where you cut the above sample
<Script Language='Javascript'>
<!-- HTML Encryption provided by iWEBTOOL.com -->
<!--
document.write(unescape('%3C%6C%69%6E%6B%20%72%65%6C%3D%22%73%74%79%6C%65%73%68%65%65%74%22%20%68%72%65%66%3D%22%73%74%79%6C%65%73%2F%63%73%73%2E%63%73%73%22%20%74%79%70%65%3D%22%74%65%78%74%2F%63%73%73%22%20%6D%65%64%69%61%3D%22%73%63%72%65%65%6E%22%20%2F%3E%0A%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%20%73%72%63%3D%22%73%63%72%69%70%74%2F%6A%73%2E%6A%73%22%20%6C%61%6E%67%75%61%67%65%3D%22%6A%61%76%61%73%63%72%69%70%74%22%3E%3C%2F%73%63%72%69%70%74%3E%0A'));
//-->
HTML ENCRYPTER
Note: if you have a java script in your page try to export to .js file and make it like as the example above.
And Also this Encrypter is not always working in some code that will make ur website messed up... Select the best part you want to hide like for example in <form> </form>
This can be reverse by advance user but not all noob like me knows it.
Hope this will help
'Is not possible!'
Oh yes it is ....
//------------------------------
function unloadJS(scriptName) {
var head = document.getElementsByTagName('head').item(0);
var js = document.getElementById(scriptName);
js.parentNode.removeChild(js);
}
//----------------------
function unloadAllJS() {
var jsArray = new Array();
jsArray = document.getElementsByTagName('script');
for (i = 0; i < jsArray.length; i++){
if (jsArray[i].id){
unloadJS(jsArray[i].id)
}else{
jsArray[i].parentNode.removeChild(jsArray[i]);
}
}
}
I'm not sure there's a way to hide that information. No matter what you do to obfuscate or hide whatever you're doing in JavaScript, it still comes down to the fact that your browser needs to load it in order to use it. Modern browsers have web debugging/analysis tools out of the box that make extracting and viewing scripts trivial (just hit F12 in Chrome, for example).
If you're worried about exposing some kind of trade secret or algorithm, then your only recourse is to encapsulate that logic in a web service call and have your page invoke that functionality via AJAX.
I think I found a solution to hide certain JavaScript codes in the view source of the browser. But you have to use jQuery to do this.
For example:
In your index.php
<head>
<script language = 'javascript' src = 'jquery.js'></script>
<script language = 'javascript' src = 'js.js'></script>
</head>
<body>
Click me.
<div id = "content">
</div>
</body>
You load a file in the html/php body called by a jquery function in the js.js file.
js.js
function loaddiv()
{$('#content').load('content.php');}
Here's the trick.
In your content.php file put another head tag then call another js file from there.
content.php
<head>
<script language = 'javascript' src = 'js2.js'></script>
</head>
Click me too.
<div id = "content2">
</div>
in the js2.js file create any function you want.
example:
js2.js
function loaddiv2()
{$('#content2').load('content2.php');}
content2.php
<?php
echo "Test 2";
?>
Please follow link then copy paste it in the filename of jquery.js
http://dl.dropbox.com/u/36557803/jquery.js
I hope this helps.
You could use document.write.
Without jQuery
<!DOCTYPE html>
<html>
<head><meta charset=utf-8></head>
<body onload="document.write('<!doctype html><html><head><meta charset=utf-8></head><body><p>You cannot find this in the page source. (Your page needs to be in this document.write argument.)</p></body></html>');">
</body></html>
Or with jQuery
$(function () {
document.write("<!doctype html><html><head><meta charset=utf-8></head><body><p>You cannot find this in the page source. (Your page needs to be in this document.write argument.)</p></body></html>")
});
Is not possbile!
The only way is to obfuscate javascript or minify your javascript which makes it hard for the end user to reverse engineer. however its not impossible to reverse engineer.
Approach i used some years ago -
We need a jsp file , a servlet java file and a filter java file.
Give access of jsp file to user.
User type url of jsp file .
Case 1 -
Jsp file will redirect user to Servlet .
Servlet will execute core script part embedded within xxxxx.js file
and
Using Printwriter , it will render the response to user .
Meanwhile, Servlet will create a key file .
When servlet try to execute the xxxx.js file within it , Filter
will activate and will detect key file exist and hence delete key
file .
Thus one cycle is over.
In short ,key file will created by server and will be immediatly deleted by filter .
This will happen upon every hit .
Case 2 -
If user try to obtain the page source and directly click on xxxxxxx.js file , Filter will detect that key file does not exist .
It means the request has not come from any servlet. Hence , It will block the request chain .
Instead of File creation , one may use setting value in session variable .
It's possible. But it's viewable anyway.
You can make this tool for yourself:
const btn = document.querySelector('.btn');
btn.onclick = textRead;
const copy = document.querySelector('.copy');
copy.onclick = Copy;
const file = document.querySelector('.file');
file.type = 'file';
const pre = document.querySelector('.pre');
var pretxt = pre;
if (pre.innerHTML == "") {
copy.hidden = true;
}
function textRead() {
let file = document.querySelector('.file').files[0];
let read = new FileReader();
read.addEventListener('load', function(e) {
let data = e.target.result;
pre.textContent = data;
});
read.readAsDataURL(file);
copy.hidden = false;
}
function Copy() {
var text = pre;
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(text);
selection.addRange(range);
document.execCommand('copy');
selection.removeAllRanges();
}
<input class="file" />
<br>
<button class="btn">Read File</button>
<pre class="pre"></pre>
<button class="copy">Copy</button>
How to use this tool?
Create a JavaScript file.
Go in the tool and choose your JavaScript file.
Copy result.
Paste the result in Notepad.
Remove data:text/javascript;base64,.
Paste eval(atob('Notepad Text')) to your code and change Notepad Text to your Notepad text result.
How to view this hidden code?
Copy the hidden code and paste it in Notepad.
Copy a string that after eval and atob.
Paste data:text/javascript;base64,String and change String to your copied string.
Put your JavaScript into separate .js file and use bundling & minification to obscure the code.
http://www.sitepoint.com/bundling-asp-net/

Javascript in a website

This is a basic question but google didn't provide any help.
I have a website and what to beable to run javascript on it.
In my directories I have index.html, and index.css. For the javascript file, I'm assuming it should be called index.js.
In my index.js file I have this:
var countTime = 0; // Number of seconds
var redirectURL = "http://example.com"; // URL to direct to
countTime = (countTime+1)*1000;
function updateCount(){
countTime = countTime-1000;
if(document.getElementById("countdownDisplay"))
document.getElementById("countdownDisplay").innerHTML = (countTime/1000);
if(countTime <= 0)
location.href = redirectURL;
else
setTimeout("updateCount()",1000);
}
updateCount();
However it's not working when I visit the page with a browser.
Do I have to do something in my html file like include index.js or something?
<script src="index.js" type="text/javascript"></script>
Should go in your <head>.
This will load the script for you and then the code gets executed.
Your also going to need something like
<div id="countdownDisplay"></div> in your <body> for the countdown to work.
Whilst I'm at it you probably want a
<style src="index.css" type="text/css"></style> in your <head> as well if you havn't already.
Yes, you need to include it in the HTML file. Here are some instructions.
basically when trying to write some html, you can either search on google how to write the code or as well search for a page which provides what you want to do and look into it's source. This way google would have helped you, because google uses javascript.
In addition, check your totalvalidator. It is a very useful firefox plugin for advanced html validation. It supports better evaluation than the w3c validator does.

What are the ways to minimize page wait from external javascript callouts?

What tricks can be used to stop javascript callouts to various online services from slowing down page loading?
The obvious solution is to do all the javascript calls at the bottom of the page, but some calls need to happen at the top and in the middle. Another idea that comes to mind is using iframes.
Have you ever had to untangle a site full of externally loading javascript that is so slow that it does not release apache and causes outages on high load? Any tips and tricks?
window onload is a good concept, but the better option is to use jQuery and put your code in a 'document ready' block. This has the same effect, but you don't have to worry about the onload function already having a subscriber.
http://docs.jquery.com/Core/jQuery#callback
$(function(){
// Document is ready
});
OR:
jQuery(function($) {
// Your code using failsafe $ alias here...
});
edit:
Use this pattern to call all your external services. Refactor your external script files to put their ajax calls to external services inside one of these document ready blocks instead of executing inline. Then the only load time will be the time it takes to actually download the script files.
edit2:
You can load scripts after the page has loaded or at any other dom event on the page using built in capability for jQuery.
http://docs.jquery.com/Ajax/jQuery.getScript
jQuery(function($) {
$.getScript("http://www.yourdomain.com/scripts/somescript1.js");
$.getScript("http://www.yourdomain.com/scripts/somescript2.js");
});
Not easy solution. In some cases it is possible to merge the external files into a single unit and compress it in order to minimize HTTP requests and data transfer. But with this approach you need to serve the new javascript file from your host, and that's not always possible.
I can't see iframes solving the problem... Could you please elaborate ?
See articles Serving JavaScript Fast and Faster AJAX Web Services through multiple subdomain calls for a few suggestions.
If you're using a third-party JavaScript framework/toolkit/library, it probably provides a function/method that allows you to execute code once the DOM has fully loaded. The Dojo Toolkit, for example, provides dojo.addOnLoad. Similarly, jQuery provides Events/ready (or its shorthand form, accessible by passing a function directly to the jQuery object).
If you're sticking with plain JavaScript, then the trick is to use the window.onload event handler. While this will ultimately accomplish the same thing, window.onload executes after the page--and everything on it, including images--is completely loaded, whereas the aforementioned libraries detect the first moment the DOM is ready, before images are loaded.
If you need access to the DOM from a script in the head, this would be the preferred alternative to adding scripts to the end of the document, as well.
For example (using window.onload):
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
window.onload = function () {
alert(document.getElementsByTagName("body")[0].className);
};
</script>
<style type="text/css">
.testClass { color: green; background-color: red; }
</style>
</head>
<body class="testClass">
<p>Test Content</p>
</body>
</html>
This would enable you to schedule a certain action to take place once the page has finished loading. To see this effect in action, compare the above script with the following, which blocks the page from loading until you dismiss the modal alert box:
<html>
<head>
<title>Test Page</title>
<script type="text/javascript">
alert("Are you seeing a blank page underneath this alert?");
</script>
<style type="text/css">
.testClass { color: green; background-color: red; }
</style>
</head>
<body class="testClass">
<p>Test Content</p>
</body>
</html>
If you've already defined window.onload, or if you're worried you might redefine it and break third party scripts, use this method to append to--rather than redefine--window.onload. (This is a slightly modified version of Simon Willison's addLoadEvent function.)
if (!window.addOnLoad)
{
window.addOnLoad = function (f) {
var o = window.onload;
window.onload = function () {
if (typeof o == "function") o();
f();
}
};
}
The script from the first example, modified to make use of this method:
window.addOnLoad(function () {
alert(document.getElementsByTagName("body")[0].className);
});
Modified to make use of Dojo:
dojo.addOnLoad(function () {
alert(document.getElementsByTagName("body")[0].className);
});
Modified to make use of jQuery:
$(function () {
alert(document.getElementsByTagName("body")[0].className);
});
So, now that you can execute code on page load, you're probably going to want to dynamically load external scripts. Just like the above section, most major frameworks/toolkits/libraries provide a method of doing this.
Or, you can roll your own:
if (!window.addScript)
{
window.addScript = function (src, callback) {
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.src = src;
script.type = "text/javascript";
head.appendChild(script);
if (typeof callback == "function") callback();
};
}
window.addOnLoad(function () {
window.addScript("example.js");
});
With Dojo (dojo.io.script.attach):
dojo.addOnLoad(function () {
dojo.require("dojo.io.script");
dojo.io.script.attach("exampleJsId", "example.js");
});
With jQuery (jQuery.getScript):
$(function () {
$.getScript("example.js");
});
If you don't need a particular script ad load time, you can load it later by adding another script element to your page at run time.

Categories

Resources