Please I have few html pages that i include some js scripts after the body . My script are working fine and successful. However, it gets messy putting the two together as the project grow. I then took the js in to an individual files . The problem is, now i reference all the files and the js codes became available for each and every html page.
I have events where I check each page load , because i want to execute or start my file on the page load . Now this page loads fire on every page load . Example below,
(function() {
$(this).on('load', function(){
console.log("the init is");
var g = true;
if(g === false)
window.location = '/';
init();
});
var init = function(){
$('#btnAdd').on('click',function(e){
e.preventDefault();
e.stopPropagation();
alert("Butoon click");
});
};
})();
Before when I embed a similar code above, it fires when my page is executed and my load became the entry point as I wanted . But now I moved them to separate html file and reference them which most have the same or similar functions. Now when i visit very html page, the onload method fires regardless , because they are all reference and available for each page.
Please is there any way I can refactor my code to separate every js file for a separate html page/url. How do I make jQuery or ajax load call with reference to the url? How do I make each file fires when its respective html/url is requested from server or loading? Any help would be appreciated
There are a couple common approaches to executing different page initialization code on different pages.
You can break the page-specific initialization code and supporting code into separate script files and only include them in <script> tags on the actual pages where they are needed.
You can use a common script file that is loaded across many pages and then within the page initialization code, you can check which page is loaded and then decide in your code which code is appropriate to run.
You can use a single common script file that includes a separate function for each separate page that needs unique initialization, but no code that calls those functions and then add one unique initialization function call to each individual page in the body of the page. This allows for the most efficient browser caching of script files and loading of fewer script files (it lets you combine and minimize most of your scripts).
For the second option, you can detect which page is loaded in your Javascript a number of different ways.
You can detect a class name on a known tag (like the body tag).
You can set a unique JS variable in each page that the initialization code can test.
You can look for the existence of certain HTML tags in the page that uniquely indicate which type of page it is. This works well when you want a particular initialization function to run on a bunch of pages that all have a certain common element.
Here's an example of option 1 (detect class name on body tag).
var m = document.body.className.match(/pageType_([^\s]+)/);
if (m) {
switch(m[1]) {
case "home":
// code here
break;
case "category":
// code here
break;
case "product":
// code here
break;
default:
// code here
break;
}
}
Here's an example of option 2 (set unique JS variable in each page):
<script>
// somewhere in each unique page
var pageType = "home";
</script>
<script>
// common script file
switch(pageType) {
case "home":
// code here
break;
case "category":
// code here
break;
case "product":
// code here
break;
default:
// code here
break;
}
</script>
Here's a scheme for detecting which unique tag exists and calling the appropriate initialization function:
if (document.getElementById("home")) {
initHome();
} else if (document.getElementById("category") {
initCategory();
}
Related
Screen width as a condition to redirect to other url during on load
-I'm trying to do this for only specific html pages, but can't seem to unless I put the redirect function (given in the link) as a script within the specific HTML page I want to invoke this.
Here is a breakdown of what I have/need
I have 3 files (desktop.html, mobile.html, script.js).
I want the desktop.html to redirect (or load) automatically the mobile.html if the screen width is < 992px.
The code I want to use will be kept in a separate JS file which is called script.js, this file already has a bunch of named functions that are within a variable. All the named functions (so far) are triggered when the user clicks on a button that corresponds. But I wont have a button that 'triggers' for redirecting to mobile.html page, as it should be automatic if the screen width is < 992px
Example of JS file
var name = {
first: function() {
<---! Does something when a button is pushed on my site --->
},
second: function() {
<---! Does something when a different button is pushed on my site --->
},
window.onload = redirectMobileHandler();
window.onresize = () => redirectMobileHandler();
function redirectMobileHandler() {
const width = Math.max(document.clientWidth || 0, window.innerWidth || 0);
if(width < 992) {
window.location = 'https://linktoyourmobilesite.com';
}
}
};
The HTML files reference the JavaScript files, so you have two options to only trigger that logic for one of your three HTML files:
Only link to the JavaScript file containing the logic in the target HTML file, by creating a new .js file that contains that logic (say index.js):
index.html
<link rel='index.js'>
index.js
var name = {
...
}
Reference the same JavaScript file in all three HTML files, but only call that function from within the target HTML file:
index.html
<button onclick='indexOnly()'>Button</button>
main.js
function indexOnly() {
var name = {
...
}
}
The latter option is preferable, as you can then make use of a template / header to handle loading all JavaScript files in a single location.
There is also technically a third option (though it is really just a combination of the two). If you use a framework like Angular, React or Vue, you'll get the concept of components, which automatically split this logic out for you, using encapsulation.
If I understand you correctly, you want to include the script to the target html file dynamically?
If so, there are numerous ways to accomplish this, for example:
var script = document.createElement('script');
script.src = 'script.js';
document.body.appendChild(script);
You can find more examples here.
However, I am not exactly sure what exactly you want to achieve. Please clarify, if my assumption is wrong.
I am developing web application in smartAdmin Template, which is fully ajax based template you can check demo here. i am facing some difficulties in this template. when i write one javascript function on some page it works on all pages.
for example
$(document).on('click', '#elementA', function(){
alert('Hello World');
});
works on other pages's element which also have same id, it is difficult to give different ids to all element as it is very large project and i am working on it since 6 months, so i thought about it and find out solution to give unique id to each pages and write script like this.
$(document).on('click', '#pageA #elementA', function(){
alert('Hello World');
});
i thought i solved the issue but, isn't function stopped working on other page's element. but when i visit #PageA 2nd time the function runs twice. actually template stores all the user defined function in local memory storage (i think, i am not sure about this) and keeps storing, until we do not refresh whole template.
ok, after long R&D i solved this my self..
i used loadscript() function to prevent loading scripts twice unnecessarily..
i wrote all the script into one file (now i will have two view pages for one page.)
earlier it was like..
A.php -> JScript + PHP & HTML
now it is like A.php -> PHP & HTML, script/A.php -> OnlyJS
as i am using codeginiter framework, and dont want others too see js by accessing it through url, i used this process.
code on my view file
loadScript("<?php echo site_url('processor/load_script/path_to_folder/script/add'); ?>");
function on Processor controller
public function load_script($path)
{
$last_segment = count($this->uri->segment_array());
$path = '';
for($i=3;$i<=$last_segment;$i++)
{
$path .= '/'.$this->uri->segment($i);
}
$this->load->view('core/ajax'.$path);
}
I am working on a project that uses AJAX to download HTML, CSS and Javascript in one singe chunk of text then appends it to an element on the page. Here is the code:
_t.stage.empty();
_t.stage.html(DATA);
This works fine.
Here is the problem:
After adding the HTML to the stage, I call this function:
if(initApp != null && typeof(initApp) == "function") initApp();// Checks for initApp(). If exists, executes.
If I load a page that has this function, then load one that does NOT have this function, the function from the first page is executed. Here is some psuedo code to understand the results.
page 1:
This is a page.
<style>...</style>
<script> function initApp(){ alert("hello"); } </script>
When this page is run, an alert box with the text 'hello' is shown.
page 2: (no initApp() function)
This is page 2.
<style>...</style>
When the page is run, an alert box with the text 'hello' is shown.
Please note: These pages are loaded with AJAX and inserted into the HTML of an already loaded page.
It is not easy to tell exactly what you're trying to do, but if what you're trying to do is make it so that some other code that calls initApp() will cause nothing to happen when it calls that, then you can simply redefine the function to a do-nothing function like this:
initApp = function() {}
The most recent definition of a function takes precedence (e.g. replaces any prior definitions).
If your newly loaded code contains an implementation of initApp() that you don't want called the second time the script is loaded, then you're out of luck. You can't stop that. You will need to change the structure of your code so that the dynamically loaded code doesn't execute stuff you don't want to be executed. There are many different ways you could do that. For example, you could have a global boolean that keeps track of whether the init code has been called yet.
var initCalled = false;
function initApp() {
if (!initCalled) {
initCalled = true;
// rest of initialization code here
}
}
initApp(); // will only actually do anything the first time it's called
// even if it is loaded more than once
It appears from the comments that you seem to think that reloading a script tag with different code will somehow make code from the previous script go away. It will not. Once a function is loaded, it stays loaded unless it is redefined to mean something else or unless some code explicitly removed a property from an object. It does not matter how the code was loaded or whether it was in the core page or an external script file.
Javascript functions that no longer exist
This is a bad premise. The functions still exist, which is obvious from the fact that the second AJAX load ended up executing it. The fact that the <script> tags are replaced and no longer in the document doesn't undefine the function. It's like asking why is your TV still broken if the burglar that broke it is no longer there.
There are two basic things you can do:
a) Clear the function explicitly yourself:
if (initApp != null && typeof(initApp) == "function") {
initApp();
delete window.initApp;
}
b) Change the function name to be unique per AJAX page (or namespace the function with the same idea), probably tied to the name of the AJAX page, so you can invoke it in a more specific manner.
First of all: 'Locally' neither means "localhost", nor "local folder". It means a code area or a code space or a code region.
I have two JS (*.js) files for my site. One is to show a news ticker and other is to load something on hover. They are conflicting, and I can't remove any one of 'em because I need 'em.
So a thing comes up to my mind is: as I can make many things locally, why not I load a js file locally? Suppose:
<?php
if('condition') {
DO IT ONCE;
}
?>
<?php
if('other_condition') {
DO STH ELSE ONCE;
}
?>
In such case, the first condition doesn't bother the second condition. Even though the first one is doing, the second one is also doing well. No conflict, nothing.
If I can load a JS locally for a specific purpose and then break the JS loading further, then if I load other JS, she won't find any JS before, because that's for a specific purpose for the specific region only.
I think I'm clear with my idea. I'm here with a WordPress site, loading code specifically for home page using is_home() function. I want such a way to load a JS file for a region, and then break it to let the other JS function properly.
If you've designed your Javascript well, you can have two scripts that don't interfere. Without seeing the actual scripts, it's hard to recommend improvement. You could introduce new scopes for each of the scripts:
script1.js
(function() {
var script_variable = document.getElementById("my_form");
script_variable.onchange = function() { /* ... */ };
})();
script2.js
(function() {
// Same name!
var script_variable = document.getElementById("other_element");
script_variable.onclick = function() { /* ... */ };
});
Load each in a separate iframe.
I'm trying to get to learn som javascript/jQuery stuff, and I'm really struggling with this one. It's basically a question of structure – how to do things in the best possible way.
I've got this function that randomly picks out a list item from one of three unordered lists (where all list items have been hidden), and shows it. Depending on what page I'm currently on, I would like to select a list item from one list in particular. All my lists are "marked" with an id, to make them unique.
I could pass an argument to my randomize function with the list id of my choice, to make it only select an item from that particular list. However, this would mean that I would have to place inline scripts in the html (one script tag with custom function call for each page), and from what I've heard inline scripts tehnd to block page rendering. And that would be bad, becuase I care about performance. Another way could be to have lots of if/else clauses, such as "if body has class the_classname -> randomize from the list with with id the_id". That would however mean that the script would have to make lots of unnecessary queries on the DOM.
Don't know if there's a term for what I'm talking about. Perhaps something like "conditional function calls" or maybe "page based function calls".
How would you tackle such a problem? I know my CSS & HTML, but am quite new to javascripting. Just trying to do the right thing...
One way would be to create a javascript file that you include in the header of all your pages. The javascript file will contain your function that takes a pageId, and returns a list item based on the page
function getListItem(pageId) {
switch (pageId) {
...
}
}
Assign an ID attribute to the BODY tag of each page, corresponding to the pageId in your javascript function:
<body id="home-page">
Then, on your page load, you can pass in the ID value to your function using jQuery:
<script type="text/javascript">
$(function() {
var listItem = getListItem($('body').attr["ID"]);
} );
</script>
This would pass in "home-page" to your javascript function and return the list item determined by the logic inside your javascript function.
The very best way to do this would be to examine the url (no DOM traversal involved, no additional external scripts, so it's fast):
var path = window.location.pathname;
if (path.indexOf('/a_unique_url') !== -1) {
// do code for the page 'a_unique_url';
} else if (path.indexOf('/another_unique_url') !== -1) {
// do code for the page 'another_unique_url';
} else {
// do default action, because none of the above were found.
}
A little more wordy on your part, but faster if you have a lot of unique operations would be to use a switch statement and the full path, like this:
var path = window.location.pathname;
switch(path) {
case '/full/path/after/domain.html':
// do code for the page '/full/path/after/domain.html';
break;
case '/some/other/path.html':
// do code for the page '/some/other/path.html';
break;
case '/yet/another/path.html':
// do code for the page '/yet/another/path.html';
break;
default:
// do default action, because none of the above were found.
break;
}
Although, if you have access to server side scripting, there are more efficient methods for these kind of operations.
To circumvent the possibility of your scripts holding up the browser it's common practice to place your scripts just before the end of your body tag.
You may even want to look into asynchronous script loading.
Friend, I don't understand exactly what you want, but I'll try to help:
the inline javascript will block your page if you put them alone in the middle of your code, but you can say to them to execute only when the page was loaded with this code:
window.onload = function (){
//call your function with the desired parameter
}
So when your page loads, the function on window.onload will be executed.
Add it from the server-side at run-time: Page.RegisterClientScriptBlock Method
Customize it with a property from the code-behind;
function myFunction() {
var theParameter = '<%# parameterName>';
// do something
}